how to access the drawable resources by name in android

hguser picture hguser · May 4, 2013 · Viewed 65.7k times · Source

In my application, I need to get the some bitmap drawables somewhere where I do not want to keep the reference R. So I create a class DrawableManager to manage the drawables.

public class DrawableManager {
    private static Context context = null;

    public static void init(Context c) {
        context = c;
    }

    public static Drawable getDrawable(String name) {
        return R.drawable.?
    }
}

Then I want to get the drawable by name somewhere like this( the car.png is put inside the res/drawables):

Drawable d= DrawableManager.getDrawable("car.png");

However as you can see, I can not access the resources by the name:

public static Drawable getDrawable(String name) {
    return R.drawable.?
}

Any alternatives?

Answer

ianhanniballake picture ianhanniballake · May 4, 2013

Note that your approach is almost always the wrong way to do things (better to pass the context into the object itself that is using the drawable than keeping a static Context somewhere).

Given that, if you want to do dynamic drawable loading, you can use getIdentifier:

Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable", 
   context.getPackageName());
return resources.getDrawable(resourceId);