Android : How to update the selector(StateListDrawable) programmatically

后端 未结 5 2131
耶瑟儿~
耶瑟儿~ 2020-11-28 06:05

I want to update the selector for a button programmatically.

I can do this with the xml file which is given below



        
5条回答
  •  广开言路
    2020-11-28 06:22

    Not enough rep to comment but the accepted answer did not work for me.

    My goal was for designers to set enabled, disabled, and pressed background colors on some button. I intended for them to use it to test colors on different displays.

    I noticed some other people mentioned it did not work for them either.

    The states that need to be defined are

    • not pressed and enabled, this is what you see when the button is enabled and not pressed.
    • pressed and enabled, this is what you see when the button is pressed and enabled
    • not enabled. This is what you see when the button is disabled

    Here is some code that will give you an idea of the states. I am using Color.Parse() to generate ints for the colors then I pass them to this method to get the StateListDrawable.

    private StateListDrawable createDrawable(int enabled, int pressed, int disabled) {
      StateListDrawable stateListDrawable = new StateListDrawable();
    
      stateListDrawable.addState(new int[] { -android.R.attr.state_pressed, android.R.attr.state_enabled }, new ColorDrawable(enabled));
      stateListDrawable.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, new ColorDrawable(pressed));
      stateListDrawable.addState(new int[] { -android.R.attr.state_enabled }, new ColorDrawable(disabled));
    
      return stateListDrawable;
    }
    

提交回复
热议问题