2014-04-22 28 views
3

StateListDrawable似乎會忽略應用於它們包含的drawable的濾色器。例如:如何將顏色過濾器應用於StateListDrawable中的特定繪圖?

StateListDrawable sld = new StateListDrawable(); 
Drawable pressedState = Context.getResources().getDrawable(R.drawable.solid_green); 

pressedState.setColorFilter(Color.RED, PorterDuff.Mode.SRC); 

sld.addState(new int[] {android.R.attr.state_pressed}, pressedState); 
// Other states... 

如果你申請sld到視圖的背景,你會期望被按下時,視圖的背景變成紅色。相反,它會變成綠色 - 沒有應用濾鏡的pressedState的顏色。

回答

5

要解決此問題,您必須根據繪圖所處的狀態將顏色過濾器應用於StateListDrawable本身。StateListDrawable的以下擴展名可以實現此目的。

public class SelectorDrawable extends StateListDrawable { 

    public SelectorDrawable(Context c) { 
     super(); 

     addState(new int[] {android.R.attr.state_pressed}, c.getResources().getDrawable(R.drawable.solid_green)); 
     // Other states... 
    } 

    @Override 
    protected boolean onStateChange(int[] states) { 
     boolean isClicked = false; 
     for (int state : states) { 
      if (state == android.R.attr.state_pressed) { 
       isClicked = true; 
      } 
     } 

     if (isClicked) 
      setColorFilter(Color.RED, PorterDuff.Mode.SRC); 
     else 
      clearColorFilter(); 

     return super.onStateChange(states); 
    } 
} 

onStateChange(int[] states)該邏輯可以進一步測試的不僅僅是按壓狀態更被延長,並且不同的濾色器可以相應地應用。

相關問題