How to access resource with dynamic name in my case?

前端 未结 5 1992
生来不讨喜
生来不讨喜 2020-12-01 04:02

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

var imageName = SERVICE.getImg();

Then, how can I get the resource with R.drawa

5条回答
  •  無奈伤痛
    2020-12-01 05:07

    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

提交回复
热议问题