androidstatelistdrawable

Create selector drawable dynamically for enable and disable state


I want to create selector dynamically for button. When button is disabled(setEnable(false)), its color should change.


Solution

  • Figured it out having silly mistake in my code.

    Method to create selector

     public static StateListDrawable createSelectorsWithStates(int[] state,
            Drawable[] drawables)
        {
        StateListDrawable stateDrawable = new StateListDrawable();
        for (int i = 0; i < state.length; i++)
        {   
            stateDrawable.addState(new int[] { state[i] }, drawables[i]);
        }
        return stateDrawable;
        }
    

    To set drawable to a button:

    Drawable enable = ResourceManager.createRectangleShape(
                 bgColor, null, borderRadius);
            enable.setAlpha((int)0.5f);
            Drawable disable = ResourceManager.createRectangleShape(
                bgColor, null, borderRadius);
            disable.setAlpha(150);
    
            ResourceManager.setDrawable(v1, ResourceManager
                .createSelectorsWithStates(new int[] {
                    android.R.attr.state_enabled,
                    -android.R.attr.state_enabled },
                    new Drawable[] { enable, disable }));