How to Create Colorstatelist Programmatically

How do I create ColorStateList programmatically?

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

set specific color to ColorStateList programmatically

Use this

ColorStateList colorStateList = new ColorStateList(
new int[][] { new int[] { R.dimen.padding_large } },
new int[] {Color.parseColor("#e3bb87")});

Android: How do I get a ColorStateList from resources?

Pass the id of the color state list resource, e.g. R.color.my_color_state_list. Color state lists belong in res/color, not res/drawable.

DrawableCompat.setTintList(drawable.mutate(),
mContext.getResources().getColorStateList(R.color.my_color_state_list));

ColorStateList doesn't work programmatically

the second parameter is the list of colors not of the id of resources. Use it like

new int[]{
getColor(R.color.DARK_GRAY_COLOR),
getColor(R.color.LIGHT_RED_COLOR),
getColor(R.color.DARK_GRAY_COLOR) }

Set a Stateful Tint for an ImageView Programatically

You are using getColor method in every tried line, but this isn't proper, that's not color, that's selector (color_red_stateful and color_green_stateful files). use Resources or preferably ContextCompat class and its useful method getColorStateList

 ColorStateList colorStateList = ContextCompat.getColorStateList(this, R.color.your_color_selector);

this colorStateList should be set as imageTintList for desired ImageViews

btw. after setting above you may use view.invalidate() method for forcing immediate apply of changes (force redraw), but in most cases, also probably yours, this won't be needed

Change selector assigned to tint programmatically

Best way I found so far is to make a new color state list programmatically and assign it to the button, yikes, the goal was to avoid setting visual attributes like colors programmatically ...

        ColorStateList buttonStates = new ColorStateList(
new int[][] {
{ -android.R.attr.state_enabled },
{}
},
new int[] {
Color.RED,
Color.BLUE
}
);

buttonMinus.setImageTintList(buttonStates);


Related Topics



Leave a reply



Submit