Get associated image (Drawable) in ImageView android

最后都变了- 提交于 2019-12-09 10:07:12

问题


i set a image to a imageview control in android:

iv.setImageResource(R.drawable.image1);

i want to get this associated Drawable, looks like:

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

thanks!


回答1:


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
}



回答2:


Define the Drawable first.

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



回答3:


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.




回答4:


use Drawable drawable=imageview.getDrawable();




回答5:


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.



回答6:


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



来源:https://stackoverflow.com/questions/7266836/get-associated-image-drawable-in-imageview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!