0

I want to access strings.xml and arrays.xml at runtime ,to parse it and read my custom provided attributes.

Is this possible? If yes, how can i access it? The thing is that I have a questionnaire and I wanted to give each question, that is defined in strings.xml a unique key, so that each question can be identified. This key I've added as a attribute.

<string key="keyForQuestion" name="question1">This is a question?</string>

Maybe there is also a way to access the name attribute? Without parsing it on my own.

1 Answer 1

1

You can acsess any xml resource by calling:

getResources(). if you're in a Activity or getActivity().getResources(). if you want to get a resource from a Fragment

Exmaple from a Activity:

  //gives us String
 String name =  getResources().getString(R.string.app_name);

 //gives us array of String
 String[] names = getResources().getStringArray(R.string.names);

 //get a specific string from its index
 String myName = names[i]

 //get a specific key from the name
   for(int i =0; i<names.lenght(); i++{
     if(names[i].equels("hello"){
         // Key is > i
       }
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Yes I know. But with that I only get the string. I want the value of the attribute key.
@FelixWeilbach this is not something in Android, so you can't do that. What you can and should do is store all your strings in a string-array and use their index as a key.
Yes I've had that idea. But imagine I delete a question or insert one.. I had then to update everything.. A lot of work..
@FelixWeilbach i just upadted my answer with 2 extra suggestions for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.