setImageResource from a string

2022-09-01 22:40:49

我想根据我的字符串更改图像视图src,我有这样的东西:

ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);

String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);

当然,它不起作用。如何以编程方式更改图像?


答案 1
public static int getImageId(Context context, String imageName) {
    return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}

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

注意:省略扩展名(例如,“.jpg”)。

示例:图像为“abcd_36.jpg”

Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);

答案 2

我不知道这是否是你的想法,但你可以设置一个图像ID(这是ints)和正确答案字符串的HashMap。

    HashMap<String, Integer> images = new HashMap<String, Integer>();
    images.put( "poland", Integer.valueOf( R.drawable.poland ) );
    images.put( "germany", Integer.valueOf( R.drawable.germany ) );

    String correctAnswer = "poland";
    imageView1.setImageResource( images.get( correctAnswer ).intValue() );

推荐