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에서 Drawable에 내가 View.setForeground()를 사용하고있어 가장 가까운 즉

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

이의 주요 단점은 그것이 23+ API에서만 사용할 수 있다는 점이다. 더 나은 솔루션을 생각해 내면 알려주세요.

+0

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

+0

감사합니다 @ ChantellOsejo,하지만 나는 그 대답으로 운이 없었고, 어쨌든'Button '을 사용하지 않았습니다. – weirdo16

답변

1

xxx에서 pressedColor, defaultColordisabledColor을 얻을 수있는 사용자 지정 View을 만드는 것이 좋습니다.

다음 코드는 재료 스타일 버튼 작동합니다 :

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