Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to its resource ID (Android Studio)

I have an xml string in my values/strings.xml file

    <string name="pokemon_d">150</string>

And I have the String "150" in my controller MainActivity.java. In my MainActivity, how can I convert that String to the resource ID of the pokemon_d String in the xml file? Is this even possible?

like image 522
gciluffo Avatar asked Jan 22 '16 22:01

gciluffo


1 Answers

You can not get identifier by value, but you can make your identifier name look like a value and get it by string name,

So what I suggest,

use your String resource name something like, resource_150

<string name="resource_150">150</string>

Now here resource_ is common for your string entries in string.xml file, so in your code,

String value = "150";
int resourceId = this.getResources().
             getIdentifier("resource_"+value, "string", this.getPackageName());

Now resourceId value is as equivalent to R.string.resource_150

Just make sure here this represent your application context. In your case MainActivity.this will work.

like image 197
user370305 Avatar answered Nov 15 '22 22:11

user370305