Pear Pear - 6 months ago 22
Android Question

Get resources id from a string

How can I do something like this?

for(String name: nameArray){
ImageView i = new ImageView(this);
// the line below does not work of course
i.setBackgroundImage(R.drawable.name);
//do some stuff
}


I've searched up some solutions but most of them involves integer IDs which I do not have

Answer

Could you please check the code below?

I'm not totally sure if it works.. However, I know that you can use Resources.getIdentifier() which returns the ID. However, I'm not sure if it works with drawable as well.

for(String name: nameArray){    
    ImageView i = new ImageView(this);
    i.setBackgroundImage(getResources().getIdentifier(name, "drawable", getPackageName()));
}