androidmenuandroid-actionbar

Android action bar checkable menu item does not work/show properly?


so I am trying to get my menu item, that is show on the action bar to behave like a checkable menu option. The firs part works, meaning it is checkable and when I press it, and set in code the setChecked(true) it works. But what does not work is the visual part. There is no change in how a menu item looks on the action bar in checked and unchecked states? I tried using invalidateOptionsMenu() but that does not do the job, and not only that, with that line in my code I can't get out of the checked state?!? What happens is that invalidate OptionsMenu() seams to unset the checked state and I end up 'looping', or on every press of that menu item I keep going to the unchecked part of the code where it gets checked and with invalidate it gets unchecked I guess...

Here is the code from my XML file for menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/lenslist_menu_add"
        android:showAsAction="always"
        android:title="@string/add"/>
    <item android:id="@+id/lenslist_menu_delete"
        android:showAsAction="always"
        android:checkable="true"
        android:title="@string/delete"/>
</menu>

And here is the java code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    case R.id.lenslist_menu_add:

        return true;
    case R.id.lenslist_menu_delete:
        if (item.isChecked() == true) {
            item.setChecked(false);
            deleteMode = false;
            lensAdapter.setDeleteMode(false);
        } else {
            item.setChecked(true);
            deleteMode = true;
            lensAdapter.setDeleteMode(true);
        }
        lensAdapter.notifyDataSetChanged();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Thanks!


Solution

  • Checkable items appear only in submenus or context menus.

    You are using them as main menu items, hence it will not work.

    SOURCE: Download the API DEMOS, and open the file ApiDemos/res/menu/checkable.xml, you'll see it as a comment on line 13. I don't know why they don't mention this in the Developer Documentation

    reference with comment.: http://alvinalexander.com/java/jwarehouse/android-examples/platforms/android-2/samples/ApiDemos/res/menu/checkable.xml.shtml