'How to use different menu in fragment than in activity?

I want to have a menu for my main activity and a menu for a fragment which is contained in the main activity. The main activity menu should be removed and the fragment menu inflated when the fragment is visible. I have tried to achieve this however this is the result:

Main activity menu snippet by itself:

enter image description here

Main activity menu snippet when fragment is displayed:

enter image description here

Clearly instead of replacing the menu in the main activity I am adding to it despite having created and inflated a fragment menu.

Here is the code in the activity responsible for this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    // Depending on which fragment is used display different actions.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Here is the code in the fragment responsible for this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.friend_menu, menu);
}

Here is friend_menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
    android:icon="@drawable/ic_person_add_black_24dp"
    android:id="@+id/nav_person_add"
    android:title="Add people"
    app:showAsAction="ifRoom" />

</menu>

How do I get my desired menu (without the search action and with the add_friend action)? I realise that it may be simpler to manage this from the activity and only inflate specific fragment menus when the fragment is displayed like the comment in the activity says: // Depending on which fragment is used display different actions.



Solution 1:[1]

You could try to clear() the menu if you want to keep your structure that way.

In your Fragment

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear(); // Remove all existing items from the menu, leaving it empty as if it had just been created.
    inflater.inflate(R.menu.friend_menu, menu);
}

Solution 2:[2]

What worked for me

in your onCreateView

 public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {

     setHasOptionsMenu(true);
 }

in your onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.setGroupVisible(0,false);
    inflater.inflate(R.menu.new_menu, menu);

    super.onCreateOptionsMenu(menu, inflater);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Murat Karagöz
Solution 2 Wowo Ot