I have Activity with 3 tabs as Fragments. I also have 3 ActionBar items. On each tab only one item should be displayed and others should be in overflow menu. My code looks like this

private void updateMenuItemsVisibility()
{
    MenuItem itemAddGate = menu.findItem(R.id.action_add_gate);
    MenuItem itemAddLinking = menu.findItem(R.id.action_new_linking);
    MenuItem itemNewConversation = menu.findItem(R.id.action_new_conversation);
    MenuItemCompat.setShowAsAction(itemNewConversation,
            MenuItemCompat.SHOW_AS_ACTION_NEVER);
    MenuItemCompat.setShowAsAction(itemAddLinking, MenuItemCompat.SHOW_AS_ACTION_NEVER);
    MenuItemCompat.setShowAsAction(itemAddGate, MenuItemCompat.SHOW_AS_ACTION_NEVER);
    if (viewPager.getCurrentItem() == 0)
    {
        MenuItemCompat.setShowAsAction(itemNewConversation,
                MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    }
    if (viewPager.getCurrentItem() == 1)
    {
        MenuItemCompat.setShowAsAction(itemAddLinking, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    }
    if (viewPager.getCurrentItem() == 2)
    {
        MenuItemCompat.setShowAsAction(itemAddGate, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    }
}

and it works... on Android 4.x. On 2.1 line for hiding seems not to work. When I change tab to second tab 2 items appear, on third 3 items. Switching to previous tabs does not hide items. I'm using ActionBarCompat. Is it a bug?

edit: Actually it also behaves like this on Samsung Galaxy S (first one) running CyanogenMod on Android 4.1. So it might be connected to situation when we have physical button instead of software keys.

有帮助吗?

解决方案

I'm not quite sure but the problem may be that API < 11 do not know the SHOW_AS_ACTION_ALWAYS as the the actionbar wasn't implemented yet.

That's why you have to add 2 additional lines of code in your menus like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/new_sms"
        android:title="@string/create_sms"
        android:orderInCategory="1"
        android:showAsAction="always"
        yourapp:showAsAction="always"
        android:icon="@drawable/arrow_right" />
</menu> 

The lines xmlns:yourapp="http://schemas.android.com/apk/res-auto" and yourapp:showAsAction="always" make it possible that the icons are always seen. Even for API 7 - 10. Else the menu items will appear in the overflow menu.

I'm not sure how to implement this programmatically but you could write 3 menu ressources like that and call onSupportInvalidateOptionsMenu() to let the fragments show their own menus. If you do so don't forget to call setHasOptionsMenu(true) in the fragments' onCreate().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top