根据字符串获取可绘制对象

9

我通过json解析图像名称,现在为了显示,我需要通过图像名称获取drawable id,所以可以这样做:

background.setBackgroundResource(R.drawable.eventimage1);

当我获取图片名称时,格式如下:
image_ev1.png

好的,那么问题是什么?似乎可以通过使用if/else语句来解决。 - tyczj
@tyczj 怎么做呢?我需要将 image_ev1.png 转换为资源 int -> R.drawable.image_ev1 - Darko Petkovski
5个回答

27

使用此函数获取一个可绘制对象,当您拥有图片名称时。请注意,图片名称不包括文件扩展名。

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());

1
由于getDrawable()已经过时,最好使用ContextCompat.getDrawable。它会返回类似于return ContextCompat.getDrawable(context, context.getResources().getIdentifier(imageName, "drawable", context.getPackageName()));的内容。 - Ben
取决于您是否使用V4支持库。根据需要,还有其他选项可用。 - Kuffs
回答不错,但代码已过时,我也在上面用 Kotlin 回答了。 - Thiago

2

这将获取您的图像ID

    int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);   

如果您需要在此之后使用可绘制对象:
getResources().getDrawable(resId)

1
这里是在Kotlin中的操作方法:
// 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))
}

1
将这个方法添加到你的代码中:
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)));

1

对于Kotlin程序员(从API 22开始使用ContextCompat):

 var res = context?.let { ContextCompat.getDrawable(it,resources.getIdentifier("your_resource_name_string", "drawable", context?.getPackageName())) }

你也可以使用例如“mipmap”而不是“drawable”,如果资源放置在其他位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接