title: How to use different menu in fragment than in activity?
body: <p>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:</p>
  
  <p>Main activity menu snippet by itself:</p>
  
  <p><a href="https://i.stack.imgur.com/VCkpb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VCkpb.png" alt="enter image description here"></a></p>
  
  <p>Main activity menu snippet when fragment is displayed:</p>
  
  <p><a href="https://i.stack.imgur.com/AA03n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AA03n.png" alt="enter image description here"></a></p>
  
  <p>Clearly instead of replacing the menu in the main activity I am adding to it despite having created and inflated a fragment menu.</p>
  
  <p>Here is the code in the activity responsible for this:</p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>Here is the code in the fragment responsible for this:</p>
  
  <pre><code>@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);
  }
  </code></pre>
  
  <p>Here is friend_menu.xml:</p>
  
  <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"&gt;
  
      &lt;item
      android:icon="@drawable/ic_person_add_black_24dp"
      android:id="@+id/nav_person_add"
      android:title="Add people"
      app:showAsAction="ifRoom" /&gt;
  
  &lt;/menu&gt;
  </code></pre>
  
  <p>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: <code>// Depending on which fragment is used display different actions.</code></p>