Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access resource with dynamic name in my case?

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?

like image 392
Leem Avatar asked Jul 05 '11 13:07

Leem


3 Answers

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

like image 192
nicholas.hauschild Avatar answered Nov 03 '22 22:11

nicholas.hauschild


Try this:

int id = getResources().getIdentifier(imageName, "drawable", getPackageName());
like image 40
Dark Magic Avatar answered Nov 03 '22 22:11

Dark Magic


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.

like image 14
xandy Avatar answered Nov 03 '22 23:11

xandy