How can I convert String to Drawable

Utku Soytaş picture Utku Soytaş · Feb 18, 2014 · Viewed 29.6k times · Source

I have many icon in drawable folder and I have their name as String. How can I access to drawable folder and change background imageView (or any view) use these name in dynamically. Thanks

Answer

FD_ picture FD_ · Feb 18, 2014

This can be done using reflection:

String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);

Or using Resources.getIdentifier():

String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

Then use this for setting the drawable in either case:

view.setBackground(drawable)