2012-10-05 4 views
3

라이브러리 프로젝트에 대한 내 사용자 정의보기의 배경으로 프로그래밍 방식으로 StateListDrawable을 설정하려고합니다.StateListDrawable이 작동하지 않습니다.

final TypedArray a = getContext().obtainStyledAttributes(attrs, 
      R.styleable.ActionBar); 
    int firstColor = a.getColor(
      R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000); 
    int secondColor = a 
      .getColor(R.styleable.ActionBar_backgroundGradientSecondColor, 
        0xff000000); 
    int textViewColor = a.getColor(R.styleable.ActionBar_titleColor, 
      0xffffffff); 
    int onClickColor = a.getColor(
      R.styleable.ActionBar_backgroundClickedColor, 0xff999999); 
    a.recycle(); 

    StateListDrawable sld = new StateListDrawable(); 
    GradientDrawable drawable = new GradientDrawable(
      Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor }); 
    sld.addState(new int[] { android.R.attr.state_enabled }, 
      new ColorDrawable(onClickColor)); 
    sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 

    action2.setBackgroundDrawable(sld); 
    action3.setBackgroundDrawable(sld); 
    actionBack.setBackgroundDrawable(sld); 
    pb.setBackgroundDrawable(drawable); 
    tv.setBackgroundDrawable(drawable); 
    tv.setTextColor(textViewColor); 

그러나,이 작동하지 않습니다 : 여기에 내가 뭘 무엇 그것은 항상 상태를 활성화립니다. 그려야 만 상태 일 때 버튼을 누릅니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

+0

:이 가능한 사용자 정의되고 싶어하기 때문에 XML을 사용하는 것은 옵션이 아니다는 (그것은 UI 라이브러리, 그래서는 사용자가 XML을 통해 그것을 사용자 정의 할 수 있도록하려면) – razielsarafan

답변

20

버튼을 눌렀을 때 버튼이 계속 사용 설정되어있는 것으로 생각하십니까?

당신은 순서를 반대로 시도 할 수 :

sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
sld.addState(new int[] { android.R.attr.state_enabled }, 
     new ColorDrawable(onClickColor)); 

는 아마 최초의 현재 유효한 상태가 그려되고있다.

가 누르고있는 것과 다른 모든 경우에 대한 또 다른 배경 당신은 또한 사용할 수 있습니다 때 다른 배경을 원하는 경우 :

sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
sld.addState(new int[] { StateSet.WILD_CARD }, 
     new ColorDrawable(onClickColor)); 

추가 : 난 그냥이 테스트는 다음 테스트 코드는 나를 위해 작동합니다 : 이런 경우에

Button testButton = new Button(context); 
      testButton.setText("Test"); 
      StateListDrawable sld = new StateListDrawable(); 
      GradientDrawable drawable = new GradientDrawable(
        Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED }); 
      sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
      sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW)); 
      testButton.setBackgroundDrawable(sld);   
      mainLayout.addView(testButton); 
+0

모두를 그것의 방법은 내가 그것을 눌러도 항상 state_enabled 또는 WILD_CARD 상태를 유지하게한다. – razielsarafan

+0

나는 나 자신을 테스트 해 봤는데 분명히 나를 위해 일한다. 사용자 정의 버튼보기를 사용하는 경우 어떤 이유로 든 결코 눌려 진 상태가되지 않으면 조사해야합니다. 또한 손가락으로 단추를 누르고있는 동안에 만 눌린 드로어 블이 나타나는지 확인하십시오. 버튼에서 손가락을 뗀 순간 더 이상 버튼이 눌러지지 않으므로 기본 배경이 다시 그려집니다. – Hendrik

+0

좋아, 나는 그걸 작동시킬 수 있었다. 그러나 버튼을 누를 때마다 전체 상위 레이아웃이 눌러집니다. 해당 레이아웃에서 모든 뷰 자식에 대해 드로어 블과 동일한 sld를 사용하고 있습니다. 문제입니까? – razielsarafan