2

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?

AndroidEnthusiast
  • 6,557
  • 10
  • 42
  • 56
  • 1
    Showing/hiding the action bar items; http://stackoverflow.com/questions/10692755/how-do-i-hide-a-menu-item-in-the-actionbar Usefull blog post: http://android-er.blogspot.nl/2013/05/show-and-hide-menu-item-programatically.html Checking if fragment is visible to user: http://stackoverflow.com/questions/9323279/how-to-test-if-a-fragment-view-is-visible-to-the-user – Mdlc Dec 02 '13 at 15:44

3 Answers3

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

    MenuItem item3  = menu.findItem(R.id.ID OF MENU);
    item3.setVisible(false);
}
Nitin Misra
  • 4,472
  • 3
  • 34
  • 52
  • Two questions: 1.) Are you referring to the method in the activity or the fragment? 2.) This works well with a few items but if I have many items i will have to set them false and then make them visible again when i need them.. – AndroidEnthusiast Dec 02 '13 at 15:57
  • @AndroidEnthusiast i'm referring it in fragment then make group of menu items and toggle visibility of group. – Nitin Misra Dec 02 '13 at 16:36
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)
}
1

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


Devrath
  • 42,072
  • 54
  • 195
  • 297