2013-06-24 70 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种状态:

  • 检查,并按下
  • 检查
  • 按下
  • 默认