How to access resource with dynamic name in my case?

前端 未结 5 1995
生来不讨喜
生来不讨喜 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 04:52

    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.

提交回复
热议问题