如何通过名称访问绘制资源的android名称、资源、android

2023-09-05 10:06:34 作者:毒药

在我的应用程序,我需要得到一些位图可绘制的地方在那里,我不希望保持基准研究。所以,我创建一个类 DrawableManager 管理​​可绘制。

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.?
    }
}

然后我想获得绘制的名字的地方像这样(的car.png就是把RES /绘区域内):

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?

推荐答案

请注意,您的做法几乎总是错误的方式做事情(最好通过上下文到对象本身是用绘制比保持静态上下文的地方)。

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).

鉴于这种情况,如果你想要做动态绘制负载,可以使用getIdentifier:

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);
 
精彩推荐
图片推荐