首先,对于标题我不太确定可以设置什么标题,抱歉。
好的,下面是我的问题:
我将从外部数据库接收一个字符串,例如:'picture0001'。
在 res/drawable 文件夹中,我有一张名为 picture0001 的图片。
我想将该图片设置为 ImageView 的背景(source)。
问题是,如何使用从外部数据库得到的字符串查找该图片。
非常感谢。
首先,对于标题我不太确定可以设置什么标题,抱歉。
好的,下面是我的问题:
我将从外部数据库接收一个字符串,例如:'picture0001'。
在 res/drawable 文件夹中,我有一张名为 picture0001 的图片。
我想将该图片设置为 ImageView 的背景(source)。
问题是,如何使用从外部数据库得到的字符串查找该图片。
非常感谢。
是的,你可以使用Resources.getIdentifier()
方法根据名称查找。
Context context = imageView.getContext();
int id = context.getResources().getIdentifier("picture0001", "drawable", context.getPackageName());
imageView.setImageResource(id);
虽然不够高效,但这种方法可以用来查找偶尔需要的资源。
您也可以像这样使用反射:
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);
Resources.getIdentifier
هڈ¯èƒ½و¯”è؟™ن¸ھو–¹و³•و›´ه®¹وک“م€‚ - Tim
drawable = resources.getDrawable(resources.obtainTypedArray(R.array.array_name).getResourceId(array_index, 0), context.getTheme());
- Dmitry