2

我有一個View,我創建了編程,我想在選擇它時產生連鎖效果。我能夠使用?attr/selectableItemBackground得到這個工作。不過,我也想在選擇它時設置View的背景顏色。我試過setBackgroundResource(selectableAttr),然後setBackgroundColor(colorSelectBackground),但顏色似乎覆蓋資源,所以我只有一個或另一個。這裏是我的代碼:添加?attr/selectableItemBackground以查看並設置背景顏色

int[] attrs = new int[]{R.attr.selectableItemBackground}; 
TypedArray typedArray = context.obtainStyledAttributes(attrs); 
int backRes = typedArray.getResourceId(0, 0); 

public void select() { 
    view.setSelected(true); 
    view.setBackgroundResource(backRes); 
    view.setBackground(colorSelectBackground); 
} 

public void deselect() { 
    view.setSelected(false); 
    view.setBackground(colorSelectBackground); 
} 

任何人都知道我可以同時使用?attr/selectableItemBackground,還可以設置背景顏色?謝謝!

編輯:爲了澄清,有問題的視圖不是一個按鈕,它是一個RelativeLayout

更新:我從來沒有真正找到一個好的解決方案。從TypedArray我得到的是使用View.setForeground()的最接近Drawable,即

view.setForeground(typedArray.getDrawable(0)); 

這個主要的缺點是,它只有在API可用23+。讓我知道你是否想出了一個更好的解決方案。

+0

見http://stackoverflow.com/questions/26686250/material-effect-on-button-with-background-color –

+0

感謝@ ChantellOsejo,但我對這個答案沒有任何運氣,而且我也沒有使用「Button」。 – weirdo16

回答

1

我建議創建一個自定義View,您可以從xml中獲取pressedColor,defaultColordisabledColor

下面的代碼將工作的材質風格的按鈕:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
{ 
    ColorStateList colorStates = new ColorStateList(
      new int[][]{ 
        new int[]{android.R.attr.state_pressed}, 
        new int[]{} 
      }, 
      new int[]{ 
        pressedColor, 
        defaultColor}); 

    view.setBackgroundDrawable(isEnabled ? new RippleDrawable(colorStates, getBackground(), getBackground()) 
      : new ColorDrawable(disabledColor); 
} 
else 
{ 
    StateListDrawable backgroundDrawable = new StateListDrawable(); 
    backgroundDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(isEnabled ? 
      pressedColor : disbledColor)); 
    backgroundDrawable.addState(StateSet.WILD_CARD, new ColorDrawable(isEnabled ? defaultColor : 
      disabledColor)); 
    view.setBackgroundDrawable(backgroundDrawable); 
} 
+0

感謝Ognian,'RippleDrawable'和'StateListDrawable'都顯示了漣漪效應,但背景顏色並沒有改變。 – weirdo16