Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace R.drawable."someString"

I have some Images in my project. The name of the image is stored in a String and I would like to setImageResource(R.drawable."....."); with the string of the image name but the problem is that this is not working.

How can I do this?

like image 314
Milos Cuculovic Avatar asked Feb 28 '12 11:02

Milos Cuculovic


4 Answers

this is not a right syntax, and you must getting compiler time error, before altering image resource you must know that, all resources provided an id, these ids are stored into R.java file. Ids are stored into integer format, and in your application you can fetch all these resources by these id, not by name, so you need to fetch id of resource at first, by:

String mDrawableName = "myimg";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

and then use this resID.

like image 98
jeet Avatar answered Nov 17 '22 06:11

jeet


Use

getResources().getIdentifier("NAME_OF_IMAGE", "drawable", context.getPackageName())
like image 39
Vyacheslav Shylkin Avatar answered Nov 17 '22 07:11

Vyacheslav Shylkin


See this thread. It should help you. Basically you need to get the identifier and then load using setImageResource.

like image 3
Boris Strandjev Avatar answered Nov 17 '22 07:11

Boris Strandjev


public int getIdentifier(String name, String defType, String defPackage);

name - name of the image
defType - it will be drawable for your case
defPackage - default package of your app (I think you can use getPackage() on the activity for this)

like image 1
colegu Avatar answered Nov 17 '22 06:11

colegu