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?
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.
Use
getResources().getIdentifier("NAME_OF_IMAGE", "drawable", context.getPackageName())
See this thread. It should help you. Basically you need to get the identifier and then load using setImageResource
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With