How to access resource with dynamic name in my cas

2019-01-13 10:41发布

If I get the image name as a variable like following:

var imageName = SERVICE.getImg();

Then, how can I get the resource with R.drawable.????, I tried R.drawable[imageName], but it failed. Any suggestions?

5条回答
迷人小祖宗
2楼-- · 2019-01-13 10:54

Use this function

public static String getResourceString(String name, Context context) {
    int nameResourceID = context.getResources().getIdentifier(name,
            "string", context.getApplicationInfo().packageName);
    if (nameResourceID == 0) {
        throw new IllegalArgumentException(
                "No resource string found with name " + name);
    } else {
        return context.getString(nameResourceID);
    }
}
查看更多
劫难
3楼-- · 2019-01-13 10:57

You can use getIdentifier method which will give you the resource id by it's name. Check this thread for more details.

查看更多
Juvenile、少年°
4楼-- · 2019-01-13 11:03

You need reflection.

Suppose you have R.drawable.image1, if you wanna access it via the String name "image1", following should work:

String Name = "image1";
int id = R.drawable.class.getField(Name).getInt(null);

But notice it only get the Id of the image, you still need the inflater to get the actual drawable from it.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-13 11:07

Try this:

int id = getResources().getIdentifier(imageName, "drawable", getPackageName());
查看更多
【Aperson】
6楼-- · 2019-01-13 11:08
int id = getResources().getIdentifier(imageName, type, package);

This will get you the ID of the resource you are looking for. With it, you can then access the resource from the R class.

Using only the name parameter:

You can also include all the 3 info in the "name" parameter using the following format: "package:type/image_name", something like:

int id = getResources().getIdentifier("com.my.app:drawable/my_image", null, null);

This is useful when you're working with external components or libraries that you can't, or don't want to, change how getIdentifier() is called. e.g.: AOSP Launcher3

查看更多
登录 后发表回答