How do I create ColorStateList programmatically?
Sometimes this will be enough:
int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);
The first dimension is an array of state sets, the second ist the state set itself. The colors array lists the colors for each matching state set, therefore the length of the colors array has to match the first dimension of the states array (or it will crash when the state is "used"). Here and example:
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_pressed}, //1
new int[]{android.R.attr.state_focused}, //2
new int[]{android.R.attr.state_focused, android.R.attr.state_pressed} //3
},
new int[] {
Color.RED, //1
Color.GREEN, //2
Color.BLUE //3
}
);
hope this helps.
EDIT example: a xml color state list like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/white"/>
<item android:color="@color/black"/>
</selector>
would look like this
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{}
},
new int[] {
context.getResources().getColor(R.color.white),
context.getResources().getColor(R.color.black)
}
);
See http://developer.android.com/reference/android/R.attr.html#state_above_anchor for a list of available states.
If you want to set colors for disabled, unfocused, unchecked states etc. just negate the states:
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.RED,
Color.GREEN,
Color.BLUE
};
ColorStateList myList = new ColorStateList(states, colors);