在Android中获取ImageView中关联的图片(Drawable)

15

我已经在Android中将一张图片设置为ImageView控件:

iv.setImageResource(R.drawable.image1);
我想获取与之相关的Drawable,看起来像这样:
Drawable myDrawable = iv.getImageResource(); //wrong

你能详细说明一下吗?我有些困惑,不太明白你想要什么。 - Nikunj Patel
8个回答

38

您可以通过以下方式获取drawable:

Drawable myDrawable = iv.getDrawable();
您可以将其与可绘制资源进行比较,例如:
if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
    //do work here
}

4
对我也没用,但它却有勾号。 - IcedDante
也许可以使用 #equals() 代替 ==?实际上,不确定Drawable是否可以这样比较。也许还有另一种方法(比如使用比较器类)? - milosmns
Drawables可以直接比较,没有任何问题。 - A.J.
它不起作用,在比较后返回false? - user13651827

9
首先需要定义可绘制对象(Drawable)。
Drawable myDrawable = getResources().getDrawable(R.drawable.image1);
iv.setImageDrawable(myDrawable);

这里需要澄清一下,由于 getDrawable(getContext(), R.drawable.image1).getConstantState() 的状态值每次都会改变,因此不建议使用 getConstantState。因此,这是最好的答案。 - Sandeep

8
很遗憾,没有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();
}

我希望这能帮助到您,它确实使我的工作更加容易。


我正在寻找一种解决方案,使图像视图上的图像资源发生变化。我想根据当前资源的行为来了解它。这个解决方案不起作用,因为我们必须在设计时使用资源ID初始化标签属性。对吗? - hasan
您可以随时添加或更改标签。此外,根据您要完成的具体任务,ViewFlipper可能是需要考虑的选择。 - Anonsage
我正在使用一个外部库来下载图片并在ImageView上更改图片。我不想修改库,因此我实现了另一种解决方案。谢谢。 - hasan

5

use Drawable drawable=imageview.getDrawable();


谢谢!我如何将其与DrawableResource(R.drawable.image1)进行比较? - thenosic
@thenosic,你可以进行比较。检查一下我的答案。 - A.J.

2

您可以像比较可绘制资源一样比较

     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.

0

如果您可以使用视图的id成员变量,这是一种简单的方法:只需使用v.setId()存储R.drawable id。然后使用v.getId()获取它。


0

getResources().getDrawable()现在已经过时了,只需使用getDrawable(R.id.myImage)即可。


0
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() 是关键


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接