java 来自字符串的 setImageResource

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6783327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:15:16  来源:igfitidea点击:

setImageResource from a string

javaandroid

提问by Badr Hari

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

我想根据我的字符串更改 imageview src,我有这样的事情:

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

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

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

当然是行不通的。如何以编程方式更改图像?

回答by james

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

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

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

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

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

Example: image is "abcd_36.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);

回答by Noah

I don't know if this is what you had in mind at all, but you could set up a HashMap of image id's (which are ints) and Strings of correct answers.

我不知道这是否是您的想法,但是您可以设置图像 ID(它们是整数)的 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() );