我通过json解析图片名称,现在要显示,我必须通过图片名称来获取drawable id,这样才能做到这一点。
background.setBackgroundResource(R.drawable.eventimage1);
当我得到图像名称时,格式是这样的:
image_ev1.png
当你有了图像名后,就使用这个函数来获取drawable。注意,图像名称不包括文件扩展名。
public static Drawable GetImage(Context c, String ImageName) {
return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}
然后只需使用 "R.drawable.eventimage1 "就可以了。setBackgroundDrawable
方法,如果你只想知道ID,就不要用getDrawable parti.e.
如果你只想要ID,就省去getDrawable部分,例如
return c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName());
这将得到你的图像ID
int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);
如果你需要一个可绘制的之后。
getResources().getDrawable(resId)
在你的代码中加入这个方法。
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
然后检索你的图像
Context ctx = getApplicationContext();
background.setBackgroundResource(getResourceID("image_ev1", "drawable", ctx)));
对于Kotlin程序员(API 22的ContextCompat)。
var res = context?.let { ContextCompat.getDrawable(it,resources.getIdentifier("your_resource_name_string", "drawable", context?.getPackageName())) }
如果资源被放置在其他位置,你也可以使用例如 "mipmap "代替 "drawable"。