Badr Hari Badr Hari - 1 year ago 157
Android Question

setImageResource from a string

I would like to change the imageview src based on my string, I have something like this:

ImageView imageView1 = (ImageView)findViewById(;

String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;

Of course it doesnt work. How can I change the image programmatically?

Answer Source
public static int getImageId(Context context, String imageName) {
    return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());

use: imageView1.setImageResource(getImageId(this, correctAnswer);

Note: leave off the extension (eg, ".jpg").

Example: image is "abcd_36.jpg"

Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download