关于ColorStateList

ColorStateList用于加载动态设置背景或者颜色的XML.
1.加载如下的XML
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white" />
<item android:state_pressed="false" android:color="@color/red" />
<item android:state_focused="true" android:color="@color/gray" />
<item android:state_focused="false" android:color="@color/d_blue" />
</selector>

2.也可以直接通过代码实现以上XML的效果.如下
  使用构造器 public ColorStateList(int[][] states, int[] colors)
  具体例子:
    private ColorStateList createSelector() {
    int statePressed = android.R.attr.state_pressed;
    int stateFocesed = android.R.attr.state_focused;
    int[][] state = {{statePressed},{-statePressed},{stateFocesed},{-stateFocesed}};
    int color1 = getResources().getColor(R.color.white);
    int color2 = getResources().getColor(R.color.red);
    int color3 = getResources().getColor(R.color.gray);
    int color4 = getResources().getColor(R.color.d_blue);
    int[] color = {color1, color2, color3, color4};
    ColorStateList colorStateList = new ColorStateList(state,color);
    return colorStateList;
    }

你可能感兴趣的:(color)