首页 > 解决方案 > Android Fragment Menus

问题描述

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.

标签: androidandroid-fragmentsmenumenuitemoncreateoptionsmenu

解决方案


在每个片段OnCreateOnCreateView方法中,确保您setHasOptionMenu(true)按如下方式调用。

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

还要检查你是否在打电话super.onCreateOptionsMenu

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

推荐阅读