2013-01-16 49 views
1

我想比较视图背景与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 
+0

你需要什么用的? –

+0

@deville我需要检查视图是否设置了背景?如果设置然后改变或者不要这样做 – Goofy

+0

比较两个drawable(例如潜在的大对象,BitmapDrawables)看起来效率不高。 –

回答

1

1)更换

if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back)) 

if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back).getConstantState()) 

这将解决incompatible operand types Drawable.Constant State and Drawable错误。

2)如果你无法比较两个位图,那么你可以使用下面的方法。

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; 
} 

3)或者,您可以分配两个不同TAG的背景图像和比较TAG而不是只直接比较绘制的。 您还可以设置背景的TAG作为绘制的ID和如下所述进行比较,

Object tag = bgView.getTag(); 
int backgroundId = R.drawable.bg_image; 
if(tag != null && ((Integer)tag).intValue() == backgroundId) { 
    //do your work. 
} 
+0

现在会比较2个背景图片吗? – Goofy

+0

我想比较它在ontouch取消使用TAG但不工作?任何想法 – Goofy

+0

回答更新,希望这将解决问题,或者你会得到解决它的一些暗示。 –

相关问题