我已经在Android中将一张图片设置为ImageView
控件:
iv.setImageResource(R.drawable.image1);
我想获取与之相关的Drawable,看起来像这样:Drawable myDrawable = iv.getImageResource(); //wrong
您可以通过以下方式获取drawable:
Drawable myDrawable = iv.getDrawable();
您可以将其与可绘制资源进行比较,例如:if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
//do work here
}
#equals()
代替 ==
?实际上,不确定Drawable是否可以这样比较。也许还有另一种方法(比如使用比较器类)? - milosmnsDrawable myDrawable = getResources().getDrawable(R.drawable.image1);
iv.setImageDrawable(myDrawable);
getDrawable(getContext(), R.drawable.image1).getConstantState()
的状态值每次都会改变,因此不建议使用 getConstantState。因此,这是最好的答案。 - SandeepgetImageResource()
或getDrawableId()
。但是,我通过使用ImageView标签创建了一个简单的解决方法。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();
}
我希望这能帮助到您,它确实使我的工作更加容易。
use Drawable drawable=imageview.getDrawable();
您可以像比较可绘制资源一样比较
if (imageView.getDrawable().getConstantState() ==
ContextCompat.getDrawable(getContext(), R.drawable.image1).getConstantState()) {
}
getResources.getDrawable is deprecated so you can use ContextCompat.getDrawable inplace of it.
如果您可以使用视图的id成员变量,这是一种简单的方法:只需使用v.setId()存储R.drawable id。然后使用v.getId()获取它。
getResources().getDrawable()现在已经过时了,只需使用getDrawable(R.id.myImage)即可。
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() 是关键