来自字符串的setImageResource

Bad*_*ari 18 java android

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

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

String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);
Run Code Online (Sandbox Code Playgroud)

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

jam*_*mes 31

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

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

注意:不要使用扩展名(例如".jpg").

示例:image是"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);
Run Code Online (Sandbox Code Playgroud)


Noa*_*oah 6

我不知道这是不是你想到的,但是你可以设置一个图像id的HashMap(它是int)和正确答案的字符串.

    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() );
Run Code Online (Sandbox Code Playgroud)