setImageResource from a string

前端 未结 2 1010
遇见更好的自我
遇见更好的自我 2020-12-05 18:50

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

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

St         


        
相关标签:
2条回答
  • 2020-12-05 19:28
    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());
    ((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);
    
    0 讨论(0)
  • 2020-12-05 19:31

    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.

        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() );
    
    0 讨论(0)
提交回复
热议问题