简体   繁体   中英

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:

在此处输入图像描述

Main activity menu snippet when fragment is displayed:

在此处输入图像描述

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.

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM