How to create selector drawable from color code programmatically in android

1.6k views Asked by At

I want to create a selector drawable with #000000 for selected and #FFFFFF for unselected state.

How can I create a drawable programmatically?

Currently I am doing it as following:

StateListDrawable states = new StateListDrawable();
ColorDrawable cdPress = new ColorDrawable(0xFF0000);
ColorDrawable cdUnPress = new ColorDrawable(0x0101DF);

states.addState(new int[] { android.R.attr.state_selected}, cdPress);
states.addState(new int[] {-android.R.attr.state_selected}, cdUnPress);

view.setBackgroundDrawable(states);
view.setSelected(isSelected);
1

There are 1 answers

5
Santhosh On

create stateListDrawable and pass to the view

   StateListDrawable stateListDrawable=new StateListDrawable();
   stateListDrawable.addState(new  int[]{android.R.attr.state_pressed}getColorDrawable(Colorcode));
   stateListDrawable.addState(new int[]{android.R.attr.state_focused},getColorDrawable(Colorcode));
    ...
    mView.setBackground(stateListDrawable);
    ...
    }
    private static Drawable getColorDrawable(int colorCode) {
            return new ColorDrawable(colorCode);
    }