Android items move from ActionBar to options menu

2019-06-14 11:27发布

问题:

I have a fragments based app where some fragments have additional actions that I want to put as buttons into the ActionBar, while some do not have any such actions. I have created an xml menu file that contains all the items for all the fragments and I show/hide at runtime depending on which fragment is currently shown using a combination of:

MenuItem item = menu.findItem(some_id);
item.setVisible(false);
MenuItem item = menu.findItem(some_other_id);
item.setVisible(true);

The problem is that when I am viewing a fragment that has no menu items, if I change device orientation and then change to a different fragment - with menu items - those items do not show up in the ActionBar but are only accessible using the device's "Menu" button.

All menu items are set as android:showAsAction="always" in the xml file, yet they consistently fail to show up in the ActionBar if the last orientation change was done while viewing a fragment with no menu items. This happens during both portrait-to-landscape and landscape-to-portrait changes.

How can I force the items to be displayed in the ActionBar at all times?

回答1:

Two points:

  1. Per the ActionBar design document, even a 10" tablet in landscape will only show a maximum of 4 items in the Action Bar per the below chart:
  2. Assuming you are under the maximum number of items that show in the ActionBar, if you want Fragments to add items to the ActionBar when they appear and remove when they hidden, you do not need to manually show/hide items within a single xml menu file, but instead add the items in each individual Fragment per the Fragments - Adding items to the Action Bar guide.