Find drawable by string
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.
2 Solutions collect form web for “Find drawable by string”
Yes, you can look it up by name using
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.