in Android, Android Code Tips

Load a resource by name

Suppose you have an image named “test.png” in your res/drawable directory.

You will probably use is as this:

Drawable mDrawable = getResources().getDrawable(R.drawable.test);

But what if you want to dynamically load the drawable by it’s name?

You can use this:

String mDrawableName = "test";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable mDrawable = getResources().getDrawable(resID);
Share