Get associated image (Drawable) in ImageView android

前端 未结 8 894
心在旅途
心在旅途 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:43

    You can compare drawable resources like

         if (imageView.getDrawable().getConstantState() == 
            ContextCompat.getDrawable(getContext(), R.drawable.image1).getConstantState()) {
    }
    

    BitmapDrawables created from the same resource will for instance share a unique -bitmap stored in their ConstantState https://developer.android.com/reference/android/graphics/drawable/Drawable.ConstantState

    getResources.getDrawable is deprecated so you can use ContextCompat.getDrawable inplace of it.
    
    0 讨论(0)
  • 2021-02-07 18:43

    This is an easy approach if you can use the view's id member variable: just store the R.drawable id using v.setId(). Then get it back with v.getId().

    0 讨论(0)
  • 2021-02-07 18:43

    getResources().getDrawable() is now deprecated, just use getDrawable(R.id.myImage);

    0 讨论(0)
  • 2021-02-07 18:52

    You can get the drawable like

    Drawable myDrawable = iv.getDrawable();
    

    You can compare it with a drawable resource like

    if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
        //do work here
    }
    
    0 讨论(0)
  • 2021-02-07 18:53
    if ((holder.fav.getDrawable().getConstantState()) == context.getResources().getDrawable(R.drawable.star_blank).getConstantState() ) {
    
      holder.fav.setImageDrawable(context.getResources().getDrawable(R.drawable.star_fill));
    
    // comparison is true
    } 
    
    

    //getConstantState() is the key

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题