Android Fragment Menus

43 Views Asked by At

In an app activity, I have four different fragments. I have added menus to each fragment with

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {}

function. But when I swipe to next fragments, and come back to previous, the menu options of the next fragment, get added to the menu in the current visible fragment. Also added the first statement menu.clear() in the onCreateOptionsMenu() but no effect. Stuck at this issue.

1

There are 1 best solutions below

0
On

Within each fragments OnCreate and OnCreateView method ensure you call setHasOptionMenu(true) as below.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_list, container, false);

    ...
    setHasOptionsMenu(true);

    return rootView;
}

also check that you are calling super.onCreateOptionsMenu

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