I have MenuItem defined this way:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_starred"
android:icon="@drawable/btn_star"
android:title="@string/description_star"
android:checkable="true"
android:checked="true"
android:orderInCategory="1"
android:showAsAction="always" />
</menu>
and btn_star.xml
defined this way:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:drawable="@drawable/btn_star_off_normal" />
<item
android:state_checked="true"
android:drawable="@drawable/btn_star_on_normal" />
</selector>
When I create an options menu using this, however, the icon is never shown in its checked state, even if the MenuItem
's isChecked()
property is true.
I'm using the ActionBarSherlock control, however, I'm getting the same result if I simply create a normal options menu and call setChecked(true)
. It still displays the btn_star_off
drawable regardless of the checked state of the item.
The onOptionsItemSelected()
method is being called correctly, and I can successfully change the checked property:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.isCheckable()) {
item.setChecked(!item.isChecked());
}
return super.onOptionsItemSelected(item);
}
Setting a breakpoint here shows the isChecked property being changed, but the icon itself is not updated to reflect the correct state.
Is there something I'm missing here? Am I doing this incorrectly? I can't figure out why this wouldn't be working correctly.
If you still want to have the behavior (checked, not checked) defined in a xml drawable, this is one way you could accomplish this:
A bit simpler way (without xml-states file):
According to the official document at http://developer.android.com/guide/topics/ui/menus.html
Hope it helps.