Hide/Show Action Bar Option Menu Item for different fragments Hide/Show Action Bar Option Menu Item for different fragments android android

Hide/Show Action Bar Option Menu Item for different fragments


Try this...

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

 @Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setHasOptionsMenu(true);}@Overridepublic void onPrepareOptionsMenu(Menu menu) {    menu.findItem(R.id.action_search).setVisible(false);    super.onPrepareOptionsMenu(menu);}


This is one way of doing this:

add a "group" to your menu:

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" >    <group        android:id="@+id/main_menu_group">         <item android:id="@+id/done_item"              android:title="..."              android:icon="..."              android:showAsAction="..."/>    </group></menu>

then, add a

Menu menu;

variable to your activity and set it in your override of onCreateOptionsMenu:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    this.menu = menu;    // inflate your menu here}

After, add and use this function to your activity when you'd like to show/hide the menu:

public void showOverflowMenu(boolean showMenu){    if(menu == null)        return;    menu.setGroupVisible(R.id.main_menu_group, showMenu);}

I am not saying this is the best/only way, but it works well for me.


To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:

Lets say you want the save button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu method of the Fragment where you view the items:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {    if (menu != null) {        menu.findItem(R.id.action_save_item).setVisible(false);    }}

NOTE: For this to work, you need the onCreate() method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true) like this:

public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setHasOptionsMenu(true);}

Might not be the best option, but it works and it's simple.