fruehbier
fruehbier

Reputation: 48

How to access the values from strings.xml dynamically?

What I want to do is to get a specific text from strings.xml dynamically. I think it will involve to access an object variable dynamically. There will be a function like:

public void getDynamicString(int level) {
  text.setText(R.string.levelText_+level);
}

And in strings.xml there will be <string name="levelText_5">Text level 5</string>

I would rather not create a list with all the text resources. Can one do this in Java/Android.

Upvotes: 2

Views: 4451

Answers (5)

Dante
Dante

Reputation: 75

I had the same problem and I fixed it using this

okey , whenever you want to access a string from strings.xml dynamically and what i mean by that is to avoid using getResources().getString(R.id.stringId) ,you create a string in which you can manipulate dynamically however you want in our case uriq ("stupid variable name") and then you create resource object which is in my example level_res and initialize it then you use this method called getIdentifier() which accepts your dynamic string as a parameter ,now u simply pass your ressource to the method getstring(mysttring)

 String uriq="level"+level_num;
 level_res=getResources();
 int mystring=getResources().getIdentifier(uriq,"string",getPackageName());
 String level=level_res.getString(mystring);

Upvotes: 0

Kenny
Kenny

Reputation: 5542

All you have to do is call

this.getString(R.string.levelText_5)

If your in an area of the program in which you have access to a Context or Application, such as a ListAdapter call:

context.getString(R.string.levelText_5)

or

application.getString(R.string.levelText_5)

if you have no access to the context or application then call:

getResources().getString(R.String.levelText_5);

To do it dynamically call:

String name = "levelText_"+level;
int id = getIdentifier(name, "string", "com.test.mypackage");
getResources().getString(id);

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

You should look at using getIdentifier(String, String, String) of the Resources class.

Upvotes: 0

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

Use the method getIdentifier(name, defType, defPackage) of the Resources class to get the id of a resource by name. Then you can do a normal getString(id) from the same class.

EDIT: a bit of Googling revealed this: this. You can find sample usage there.

Upvotes: 2

Mandel
Mandel

Reputation: 2988

Try: getResources().getString(R.id.stringId).

Upvotes: 0

Related Questions