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?
Asked
Active
Viewed 1.0k times
2
-
1Showing/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 Answers
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)
}

Bitcoin Cash - ADA enthusiast
- 11,457
- 16
- 83
- 103
-
+1 for that! Actually, just putting `return false;` as the only statement within `onPrepareOptionsMenu()` also removes the whole menu. – 1111161171159459134 Sep 02 '15 at 20:10
-
-
@zdd I don't know how; the fact is that `return false;` does remove the whole menu! Did you try it? – 1111161171159459134 Apr 08 '17 at 17:41
-
@1111161171159459134, we have some gap, this function return boolean in Activity but return void in Fragment, that's the difference. – zdd Apr 12 '17 at 15:49
1
What i understand with your post is::
- You have 3 fragments
- 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