如何在android中以编程方式从颜色代码创建选择器drawable

时间:2014-07-02 06:38:49

标签: android selector-drawable

我想创建一个可选的draw #000000选择器和#FFFFFF未选择状态。

如何以编程方式创建drawable?

目前我正在做以下事情:

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 个答案:

答案 0 :(得分:1)

创建stateListDrawable并传递给视图

   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);
    }