我想要比较 view background 和 drawable,但是没成功
View v1 = options.findViewById(i);
v1.findViewById(R.drawable.back);
Drawable d = v1.getBackground();
if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back)){
v1.setBackgroundResource(R.drawable.a);
}else{
view.setBackgroundResource(R.drawable.b);
}
下面是错误提示:
incompatible operand types Drawable.Constant State and Drawable
如何检查view是否设置指定的背景?
你直接
d == getResources().getDrawable(R.drawable.correct_ans_back)
如果你不能比较两个 bitmaps,可以使用下面的方法:
public boolean compareDrawable(Drawable d1, Drawable d2){
try{
Bitmap bitmap1 = ((BitmapDrawable)d1).getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
stream1.flush();
byte[] bitmapdata1 = stream1.toByteArray();
stream1.close();
Bitmap bitmap2 = ((BitmapDrawable)d2).getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, stream2);
stream2.flush();
byte[] bitmapdata2 = stream2.toByteArray();
stream2.close();
return bitmapdata1.equals(bitmapdata2);
}
catch (Exception e) {
// TODO: handle exception
}
return false;
}