Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find drawable by string [duplicate]

Tags:

android

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.

like image 830
QuinDa Avatar asked Nov 12 '12 20:11

QuinDa


2 Answers

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.

like image 65
Cat Avatar answered Nov 01 '22 00:11

Cat


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.

like image 26
Flávio Faria Avatar answered Nov 01 '22 01:11

Flávio Faria