Robin
Robin

Reputation: 10368

Android: hide action bar menu views regardless the menu items

I am using navigation drawer to switch between fragments. And my action bar menu items are different regarding to the fragments.

I want to hide the menu item views when drawer is opened. Referring to the doc, it suggest to find the menu item by ID and hide the item. However, my menu items are different with fragments, so, how can I simply hide/show the menu item views on the action bar? Is there some flag to control it?

By the way, I see in the DOC it says I can return false in onPrepareOptionsMenu() to make it not displayed, however I tried and ended up in vain. Did I misunderstand it?

public boolean onPrepareOptionsMenu (Menu menu)

Added in API level 1 Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents. The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.

Parameters menu The options menu as last shown or first initialized by onCreateOptionsMenu().

Returns You must return true for the menu to be displayed; if you return false it will not be shown.

Upvotes: 0

Views: 134

Answers (1)

Nicks
Nicks

Reputation: 16317

If people are still visiting the link, this is how we disable the options menu or options menu items for a fragment.

1) In the onCreateView() method of fragment add the following code

 setHasOptionsMenu(true);// then only we can work with the menu items.Without this onPrepareOptionsMenu() method is not called
 .

Now override the onPreparedOptionsMenu() method and hide the menu items. If you hide all the menu items the menu will not at all be shown. or use menu.clear() to clear all the menu items

@Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.menu_contacts).setVisible(false);
        --------------
        }

Upvotes: 0

Related Questions