Possible Duplicate:
Android - Open resource from @drawable String
First of all sorry for the title but I don't know exactly what title I can set.
Ok, here's my question:
I will recibe from a external database a string for example: 'picture0001'.
In the folder res/drawable I have a picture which name is picture0001.
I would like to set that picture as background (source) of a ImageView.
The question is, how can I look for this picture with the string I got from the external database.
Thank you so much.
Yes, you can look it up by name using Resources.getIdentifier()
.
Context context = imageView.getContext();
int id = context.getResources().getIdentifier("picture0001", "drawable", context.getPackageName());
imageView.setImageResource(id);
It's not efficient, but it works to look up occasional resources.
You can also use reflection like this:
Class c = Class.forName("your.project.package.R");
Field f = c.getDeclaredField("drawable");
Class d = f.getDeclaringClass();
Field f2 = d.getDeclaredField("yourstring");
int resId = f2.getInt(null);
Drawable d = getResources().getDrawable(resId);
Though, the best solution is what MarvinLabs suggested.
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