2013-01-16 36 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

回答更新,希望這將解決問題,或者你會得到解決它的一些暗示。 –

相關問題