通过字符串查找drawable

Qui*_*nDa 37 android

可能重复:
Android - 从@drawable String打开资源

首先抱歉标题,但我不确切知道我可以设置什么标题.

好的,这是我的问题:

我将从外部数据库中重新编写一个字符串,例如:'picture0001'.

在res/drawable文件夹中我有一张名为picture0001的图片.

我想将该图片设置为ImageView的背景(源).

问题是,如何使用从外部数据库获得的字符串查找此图片.

非常感谢.

Eri*_*ric 153

是的,您可以使用名称查找Resources.getIdentifier().

Context context = imageView.getContext();
int id = context.getResources().getIdentifier("picture0001", "drawable", context.getPackageName());
imageView.setImageResource(id);
Run Code Online (Sandbox Code Playgroud)

它效率不高,但它可以查找偶尔的资源.


Flá*_*ria 5

您也可以使用这样的反射:

Class c = Class.forName("your.project.package.R");
Field f = c.getDeclaredField("drawable");
Class d = f.getDeclaringClass();
Field f2 = d.getDeclaredField("yourstring");
int resId = f2.getInt(null);
Drawable d = getResources().getDrawable(resId);
Run Code Online (Sandbox Code Playgroud)

虽然,最好的解决方案是MarvinLabs建议的.

  • 我认为`Resources.getIdentifier`可能比这更简单. (3认同)