Use ColorStateList with checkable option and state_checked clause
My options menu is filled with items like:
<item
android:id="@+id/menu_bus"
android:checkable="true"
android:checked="true"
android:icon="@drawable/icon_bus"
android:title="@string/bus"
app:showAsAction="ifRoom"/>
Here's mine onOptionsItemsSelected
:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
item.setChecked(!item.isChecked());
Log.d("test", "Item " + item + " is now checked: " + item.isChecked());
ColorStateList colorStateList = getResources().getColorStateList(R.color.options_menu_colors);
Drawable d = DrawableCompat.wrap(item.getIcon());
DrawableCompat.setTintList(d, colorStateList);
item.setIcon(d);
return true;
}
As you can see, my goal is to have a widget in older android versions using the v22.1 support libraries feature.
The color is defined as such:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/accent" android:state_checked="true"/>
<item android:color="@color/secondary_text"/>
</selector>
However state_checked
does not work with checkbox menu items!
Here's the icon log preset:
D/test (11529): Item Bus is checked: false
D/test (11529): Item Bus is checked: true
D/test (11529): Item Bus is checked: false
D/test (11529): Item Bus is checked: true
I tried to switch the selector to state_pressed
: this one works! When you touch a menu item, the color changes!
So why can't it ColorStateList
work with menu items state_checked
?
PS: using this works:
int colorId = item.isChecked() ? R.color.accent : R.color.secondary_text;
int color = getResources().getColor(colorId);
DrawableCompat.setTint(d, color);
But obviously I would like something more elegant.
source to share
According to the documentation Using checked menu items , you need to manually specify the checked state, for example
if(item.isCheckable()) {
int[] state = {item.isChecked() ? android.R.attr.state_checked : android.R.attr.state_empty};
item.getIcon().setState(state);
}
source to share