15...">

How to convert String to your resource identifier (Android Studio)

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

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

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

+5
source share
3 answers

You cannot get an 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 String resource name e.g. resource_150

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

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

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

Now the value of resourceId equivalent to the value of R.string.resource_150

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

+6
source

Resource ID R.string.pokemon_d

I do not believe that you can find a resource identifier by a string value. You can make the value map and resId so that the key is the value, and the value of the map is your res identifier, if you did, you could look at it yourself, but I don’t even know why this would be useful.

+1
source

I found some tips here: Android, getting a resource id from a string?

Below is an example of how to get strings and their values ​​defined in strings.xml. The only thing you need to do is loop through and check which string holds your value. If you need to repeat this many times, it would be better to build an array. // ---------

  String strField = ""; int resourceId = -1; String sClassName = getPackageName() + ".R$string"; try { Class classToInvestigate = Class.forName(sClassName); Field fields[] = classToInvestigate.getDeclaredFields(); strField = fields[0].getName(); resourceId = getResourceId(strField,"string",getPackageName()); String test = getResources().getString(resourceId); Toast.makeText(this, "Field: " + strField + " value: " + test , Toast.LENGTH_SHORT).show(); } catch (ClassNotFoundException e) { Toast.makeText(this, "Class not found" , Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, "Error: " + e.getMessage() , Toast.LENGTH_SHORT).show(); } } public int getResourceId(String pVariableName, String pResourcename, String pPackageName) { try { return getResources().getIdentifier(pVariableName, pResourcename, pPackageName); } catch (Exception e) { e.printStackTrace(); return -1; } } 
0
source

Source: https://habr.com/ru/post/1241279/


All Articles