开发者

Get associated image (Drawable) in ImageView android

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

iv.setImageResource(R.drawable.image1);
开发者_StackOverflow

I want to get this associated Drawable, looks like:

Drawable myDrawable = iv.getImageResource(); //wrong


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
}


Define the Drawable first.

Drawable myDrawable = getResources().getDrawable(R.drawable.image1);
iv.setImageDrawable(myDrawable);


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.


use Drawable drawable=imageview.getDrawable();


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.


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().


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜