Get associated image (Drawable) in ImageView android

前端 未结 8 898
心在旅途
心在旅途 2021-02-07 18:34

I have set an image to an ImageView control in android:

iv.setImageResource(R.drawable.image1);

I want to get this associated Drawab

8条回答
  •  执笔经年
    2021-02-07 18:56

    Unfortunately, there is no getImageResource() or getDrawableId(). But, I created a simple workaround by using the ImageView tags.

    In onCreate():

    imageView0 = (ImageView) findViewById(R.id.imageView0);
    imageView1 = (ImageView) findViewById(R.id.imageView1);
    imageView2 = (ImageView) findViewById(R.id.imageView2);
    
    imageView0.setTag(R.drawable.apple);
    imageView1.setTag(R.drawable.banana);
    imageView2.setTag(R.drawable.cereal);
    

    Then, if you like, you can create a simple function to get the drawable id:

    private int getImageResource(ImageView iv) {
        return (Integer) iv.getTag();
    }
    

    I hope this helps you, it sure made my work easier.

提交回复
热议问题