Anukool Anukool - 10 days ago 8
Android Question

How do I create ColorStateList programmatically?

I am trying to create a

ColorStateList
programatically using this:

ColorStateList stateList = new ColorStateList(states, colors);


But I am not sure what are the two parameters.

As per the documentation:


public ColorStateList (int[][] states, int[] colors)


Added in API level 1

Creates a ColorStateList that returns the specified mapping from states to colors.


Can somebody please explain me how to create this?

What is the meaning of two-dimensional array for states?

Answer

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