80

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?

4

6 回答 6

179

请注意,您的方法几乎总是错误的做事方式(最好将上下文传递到使用可绘制对象的对象本身,而不是在Context某处保持静态)。

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

Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable", 
   context.getPackageName());
return resources.getDrawable(resourceId);
于 2013-05-04T02:09:00.917 回答
23

你可以做这样的事情。-

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"
    ....
于 2013-05-04T02:12:37.470 回答
9

修改图片内容:

    ImageView image = (ImageView)view.findViewById(R.id.imagenElement);
    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());
    image.setImageResource(resourceImage);
于 2016-05-18T17:02:18.657 回答
6

使用 Kotlin

fun Context.getResource(name:String): Drawable? {
    val resID = this.resources.getIdentifier(name , "drawable", this.packageName)
    return ActivityCompat.getDrawable(this,resID)
}

我把它写成扩展函数,所以它可以在代码中的任何地方使用。

注意:在 Javacontext.getResources().getDrawable(resourceId);中已弃用。

注意:文件名,是没有扩展名的名称,例如“a.png”名称将是“a”

于 2020-01-15T20:20:25.703 回答
1

你可以这样实现

int resourceId = getResources().getIdentifier("your_drawable_name", "drawable", getPackageName());

在 Imageview 中设置resourceId

imageView.setImageResource(resourceId);
于 2020-11-04T18:09:12.617 回答
0

如果你需要 int 资源

 Resources resources = context.getResources();
 int resourceId = resources.getIdentifier("eskb048", "drawable",context.getPackageName());
 // return like: R.drawable.eskb048.png

如果您需要 Drawable 检查第一个答案对所有人都是正确的

于 2020-01-24T19:01:09.240 回答