-1

I have to convert a string like "R.drawable.photo" into an integer that contain the same thing. How can I do?

<string name="id1">R.drawable.photo</string>

I need to get an ID that contain "R.drawable.photo"

forpas
  • 160,666
  • 10
  • 38
  • 76
Simone Gaggio
  • 73
  • 1
  • 1
  • 13
  • Can you perhaps share a bit more about your use case? It's unclear what IDs you're planning to translate from/to. – Kevin Coppock Jan 04 '19 at 21:33
  • I need to obatian the id "R.drawable.photo" from the string – Simone Gaggio Jan 04 '19 at 21:35
  • I think the bigger question here is _why_ you have to do this? Considering that `R.string.id1` will never change during the lifetime of the app, why would you try to "parse" `R.string.id1` into `R.drawable.photo` instead of just using `R.drawable.photo` directly? – Ben P. Jan 04 '19 at 21:39
  • Because in my application there is an array in a xml file that contain a lot of strings and I need to extract one randomly and use it to set an ImageView – Simone Gaggio Jan 04 '19 at 21:41
  • Why not instead have an array of drawable ids inside your java/kotin code? – Ben P. Jan 04 '19 at 21:47

2 Answers2

1

Get it with the getIdentifier() method:

int id = getResources().getIdentifier("photo", "drawable", getPackageName());

getResources() and getPackageName() may need a Context if this code is not inside an activity:

int id = context.getResources().getIdentifier("photo", "drawable", context.getPackageName());

If the string has the R.drawable. prefix, then:

String str = "R.drawable.photo"
int id = getResources().getIdentifier(str.replace("R.drawable.", ""), "drawable", getPackageName());
forpas
  • 160,666
  • 10
  • 38
  • 76
0
int resID = getResources().getIdentifier("myString", 
        "drawable", getPackageName());

replace myString above with your value of string, which is "photo"

Mohammed Siddiq
  • 477
  • 4
  • 16