2012-09-08 63 views
2

我有一個代碼可以在點擊時改變圖像按鈕的色調。button.setColorFilter無法正常工作

這裏的Java代碼

button.setOnTouchListener(new OnTouchListener() { 

     public boolean onTouch(View v, MotionEvent me) 
     { 
      if (me.getAction() == MotionEvent.ACTION_DOWN) 
      { 

       button.setColorFilter(Color.argb(150, 155, 155, 155)); 

      } 

      else if (me.getAction() == MotionEvent.ACTION_UP) 

      { 
       button.setColorFilter(Color.argb(0, 155, 155, 155)); 
       } 
      return false; 
     } 

    }); 

的代碼是在這個XML做工精細,點擊後按鈕變暗。

<ImageButton 
    android:id="@+id/schedule" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_x="138dp" 
    android:layout_y="169dp" 
    android:src="@drawable/schedule" 
    /> 

但它不是在這個XML上工作,點擊時按鈕不會變暗。

<ImageButton 
    android:id="@+id/schedule" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_x="138dp" 
    android:layout_y="169dp" 
    android:background="@drawable/schedule" 
    /> 

爲什麼如果我使用android:background setColorFilter不起作用?但如果我使用android:src,它工作正常。

回答

6

簡單的回答是:

  • android:background屬性指的是View類的方法,
  • android:src指的ImageView的方法,

每類維護他們的自己的背景資源。因此,當您調用ImageView方法setColorFilter()時,會將篩選器應用於其本地背景資源(由src設置的篩選器)並且setColorFilter()不知道由background設置的View資源。