AndroidEnthusiast
AndroidEnthusiast

Reputation: 6657

Hide menu options in action bar

I have one activity with 3 fragments (not tabs). I have several action bar items and I would like to hide them when a certain fragment is present. How can i go about this?

Upvotes: 2

Views: 10080

Answers (3)

If you wish to hide ALL menu items, just do:

@Override
public void onAttach(final Activity activity) {

    super.onAttach(activity);

    setHasOptionsMenu(true);
}

@Override
public void onPrepareOptionsMenu(final Menu menu) {

    super.onPrepareOptionsMenu(menu);

    menu.clear();//This removes all menu items (no need to know the id of each of them)
}

Upvotes: 3

Devrath
Devrath

Reputation: 42824

What i understand with your post is::

  1. You have 3 fragments
  2. You have 3 different set of actionbar buttons for 3 fragments

My preferred approach::You can also find the menu items which you dont want to display in your current fragment and set their visibility

MenuItem item = menu.findItem(<id>);
item.setVisible(<true/false>);

ex::

MenuItem item1 = menu.findItem(R.id.searchID);
item1.setVisible(false);

You can also use this post for a different approach to handle this problem


Upvotes: 1

Nitin Misra
Nitin Misra

Reputation: 4522

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    MenuItem item3  = menu.findItem(R.id.ID OF MENU);
    item3.setVisible(false);
}

Upvotes: 5

Related Questions