如何在Android中按名称访问可绘制资源

在我的应用程序中,我需要将一些位图可绘制对象放置在不想保留reference的位置R。因此,我创建了一个类DrawableManager来管理可绘制对象。


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

    }

}

然后我想通过类似这样的名称来获取drawable(car.png放在res / drawables里面):


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

但是,如您所见,我无法通过名称访问资源:


public static Drawable getDrawable(String name) {

    return R.drawable.?

}

有其他选择吗?


温温酱
浏览 485回答 3
3回答

慕沐林林

请注意,您的方法几乎总是错误的处理方式(最好是将上下文传递给使用drawable的对象本身,而不是在Context某个地方保持静态)。鉴于此,如果要进行动态可绘制加载,则可以使用getIdentifier:Resources resources = context.getResources();final int resourceId = resources.getIdentifier(name, "drawable",    context.getPackageName());return resources.getDrawable(resourceId);

holdtom

你可以做这样的事情。public static Drawable getDrawable(String name) {&nbsp; &nbsp; Context context = YourApplication.getContext();&nbsp; &nbsp; int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName());&nbsp; &nbsp; return context.getResources().getDrawable(resourceId);}为了从任何地方访问上下文,您可以扩展Application类。public class YourApplication extends Application {&nbsp; &nbsp; private static YourApplication instance;&nbsp; &nbsp; public YourApplication() {&nbsp; &nbsp; &nbsp; &nbsp; instance = this;&nbsp; &nbsp; }&nbsp; &nbsp; public static Context getContext() {&nbsp; &nbsp; &nbsp; &nbsp; return instance;&nbsp; &nbsp; }}并将其映射到您的Manifest application标签中<application&nbsp; &nbsp; android:name=".YourApplication"&nbsp; &nbsp; ....

qq_笑_17

修改图片内容:&nbsp; &nbsp; ImageView image = (ImageView)view.findViewById(R.id.imagenElement);&nbsp; &nbsp; int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());&nbsp; &nbsp; image.setImageResource(resourceImage);
打开App,查看更多内容
随时随地看视频慕课网APP