我通过json解析图像名称,现在为了显示,我需要通过图像名称获取drawable id,所以可以这样做:
background.setBackgroundResource(R.drawable.eventimage1);
当我获取图片名称时,格式如下:
image_ev1.png
我通过json解析图像名称,现在为了显示,我需要通过图像名称获取drawable id,所以可以这样做:
background.setBackgroundResource(R.drawable.eventimage1);
image_ev1.png
使用此函数获取一个可绘制对象,当您拥有图片名称时。请注意,图片名称不包括文件扩展名。
public static Drawable GetImage(Context c, String ImageName) {
return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}
那么只需使用 setBackgroundDrawable
方法。
如果您只需要ID,则省略 getDrawable 部分,即:
return c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName());
return ContextCompat.getDrawable(context, context.getResources().getIdentifier(imageName, "drawable", context.getPackageName()));
的内容。 - Ben这将获取您的图像ID
int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);
getResources().getDrawable(resId)
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileIntId = getDrawableIntByFileName(context, "app_my_bg_drawable")
fun getDrawableIntByFileName(context: Context, fileName: String): Int {
return context.resources.getIdentifier(fileName, "drawable", context.packageName)
}
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileDrawable = getDrawableByFileName(context, "app_my_bg_drawable")
fun getDrawableByFileName(context: Context, fileName: String): Drawable? {
return ContextCompat.getDrawable(context, context.resources.getIdentifier(fileName, "drawable", context.packageName))
}
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())) }
image_ev1.png
转换为资源 int ->R.drawable.image_ev1
。 - Darko Petkovski