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

hgu*_*ser 65 android drawable

在我的应用程序中,我需要在某些地方获取一些位图drawable,我不想保留引用R.所以我创建了一个类DrawableManager来管理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.?
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想通过这个名字得到drawable(car.png放在res/drawables中):

Drawable d= DrawableManager.getDrawable("car.png");
Run Code Online (Sandbox Code Playgroud)

但是正如您所看到的,我无法通过名称访问资源:

public static Drawable getDrawable(String name) {
    return R.drawable.?
}
Run Code Online (Sandbox Code Playgroud)

任何替代品?

ian*_*ake 148

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

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

Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable", 
   context.getPackageName());
return resources.getDrawable(resourceId);
Run Code Online (Sandbox Code Playgroud)

  • @PratikMandrekar - 假设您正在尝试获取诸如`R.drawable.your_image`之类的资源,您需要使用`resource.getIdentifier("your_image","drawable",context.getPackageName())` - 具体代码很难看出有什么问题. (2认同)

ssa*_*tos 22

你可以这样做.-

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);
}
Run Code Online (Sandbox Code Playgroud)

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

public class YourApplication extends Application {

    private static YourApplication instance;

    public YourApplication() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<application
    android:name=".YourApplication"
    ....
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我从来不知道我之前可以通过这种方式获得上下文.它似乎会使代码更清晰. (3认同)

小智 7

修改图片内容:

    ImageView image = (ImageView)view.findViewById(R.id.imagenElement);
    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());
    image.setImageResource(resourceImage);
Run Code Online (Sandbox Code Playgroud)


Mah*_*rok 6

使用 Kotlin

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

Run Code Online (Sandbox Code Playgroud)

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

注:context.getResources().getDrawable(resourceId);弃用Java编写的。

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