如何通过名称访问绘制资源的android [英] how to access the drawable resources by name in android

查看:168
本文介绍了如何通过名称访问绘制资源的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我需要得到一些位图可绘制的地方在那里,我不希望保持基准研究。所以,我创建一个类 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).

鉴于这种情况,如果你想要做动态绘制负载,可以使用<一个href="http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29">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);

这篇关于如何通过名称访问绘制资源的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆