获取ImageView android中的关联图像(可绘制)



我在android中为ImageView控件设置了一个图像:

iv.setImageResource(R.drawable.image1);

我想得到这个关联的Drawable,看起来像:

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

您可以获得类似的可提取文件

Drawable myDrawable = iv.getDrawable();

你可以将其与这样的可提取资源进行比较

if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
    //do work here
}

首先定义Drawable。

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

遗憾的是,没有getImageResource()getDrawableId()。但是,我通过使用ImageView标记创建了一个简单的解决方法。

在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);

然后,如果你愿意,你可以创建一个简单的函数来获得可提取的id:

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

我希望这对你有帮助,它确实让我的工作更轻松。

使用Drawable drawable=imageview.getDrawable();

您可以比较等可提取资源

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

例如,从同一资源创建的BitmapDrawables将共享存储在其ConstantState中的唯一位图https://developer.android.com/reference/android/graphics/drawable/Drawable.ConstantState

getResources.getDrawable is deprecated so you can use ContextCompat.getDrawable inplace of it.

如果您可以使用视图的id成员变量,这是一个简单的方法:只需使用v.setId((存储R.drawable id。然后使用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((是的关键

getResources((.getDrawable((现在已弃用,只需使用getDrawable(R.id.myImage(;

最新更新