为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

温温酱 2019-12-27 09:47:36
在我的应用程序中,我需要将一些位图可绘制对象放置在不想保留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.?}有其他选择吗?
查看完整描述

3 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

请注意,您的方法几乎总是错误的处理方式(最好是将上下文传递给使用drawable的对象本身,而不是在Context某个地方保持静态)。


鉴于此,如果要进行动态可绘制加载,则可以使用getIdentifier:


Resources resources = context.getResources();

final int resourceId = resources.getIdentifier(name, "drawable", 

   context.getPackageName());

return resources.getDrawable(resourceId);


查看完整回答
反对 回复 2019-12-27
?
holdtom

TA贡献1805条经验 获得超10个赞

你可以做这样的事情。


public static Drawable getDrawable(String name) {

    Context context = YourApplication.getContext();

    int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName());

    return context.getResources().getDrawable(resourceId);

}

为了从任何地方访问上下文,您可以扩展Application类。


public class YourApplication extends Application {


    private static YourApplication instance;


    public YourApplication() {

        instance = this;

    }


    public static Context getContext() {

        return instance;

    }

}

并将其映射到您的Manifest application标签中


<application

    android:name=".YourApplication"

    ....


查看完整回答
反对 回复 2019-12-27
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

修改图片内容:


    ImageView image = (ImageView)view.findViewById(R.id.imagenElement);

    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());

    image.setImageResource(resourceImage);


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 483 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信