2013-06-24 73 views
2

比較兩個繪製,這是我的問題:在onClickListener

在按鈕的第一次點擊我設置的視圖背景

public void clickOnButton(View v){ 
     if(compareDrawable(getResources().getDrawable(R.drawable.green_button), v.getBackground())) { 
      v.setBackgroundResource(R.drawable.red_button); 
     }else{ 
      v.setBackgroundResource(R.drawable.green_button); 
     } 
} 

當比較功能有這樣的代碼:

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

我已經嘗試使用這些比較中的一些:

if(v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.green_button).getConstantState())) 

if(getResources().getDrawable(R.drawable.green_button).hashCode() == v.getBackground().hashCode()) 

和XML文件的代碼是這樣的:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true" > 
    <shape> 
     <solid 
      android:color="#70c656" /> 
     <stroke 
      android:width="1dp" 
      android:color="#53933f" /> 
     <corners 
      android:radius="3dp" /> 
     <padding 
      android:left="10dp" 
      android:top="10dp" 
      android:right="10dp" 
      android:bottom="10dp" /> 
    </shape> 
</item> 
<item> 
    <shape> 
     <gradient 
      android:startColor="#70c656" 
      android:endColor="#53933f" 
      android:angle="270" /> 
     <stroke 
      android:width="1dp" 
      android:color="#53933f" /> 
     <corners 
      android:radius="4dp" /> 
     <padding 
      android:left="10dp" 
      android:top="10dp" 
      android:right="10dp" 
      android:bottom="10dp" /> 
    </shape> 
</item> 

,但他們不工作,他們每次都返回false。我怎樣才能比較這些對象?

+0

這個問題已經在這裏討論http://stackoverflow.com/questions/6120439/comparing-bitmap-images-in-an DROID – Desert

回答

0

爲什麼你需要比較Drawables來改變圖像來回?

而是使用CheckBox或其他CompoundButton和使用selector XML有4種狀態:

  • 檢查,並按下
  • 檢查
  • 按下
  • 默認