如何在调用 FragmentManager.replace() 时不调用 onCreateOptionsMenu

How to NOT call onCreateOptionsMenu when calling FragmentManager.replace()

我有一个 Toolbar 用作两个项目的 ActionBar。我只想一次显示一个,因为它们会相互替换。问题是,当我替换 Fragment 时,它会调用 onCreateOptionsMenu 并再次展开菜单,这意味着将显示相同的操作按钮,即使另一个按钮之前位于 [=12] =].我需要更改我的 Fragments 中的 ActionBar 中的任何内容,或者当显示新的 Fragment 时(使用 FragmentManager.FragmentTransaction.replace())。所以我的问题是如何在显示新片段时不调用 onCreateOptionsMenu

我不能使用 boolean,因为我仍然需要它在方向改变时重新充气。关于如何根据我的情况处理方向变化有什么建议吗?

我可以 post 编码,但它看起来更概念化,我不确定它是否有帮助。

我会 fiddle 使用 onPrepareOptionsMenu 挂钩。如果你能检测到你的菜单不应该显示,你应该从那里开玩笑 return false。根据文档:

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

You must return true for the menu to be displayed; if you return false it will not be shown.

您可以在片段中调用 setHasOptionsMenu(false);

这将防止 onCreateOptionsMenu() 在该片段添加时被调用。

我通过手动将项目添加到我的菜单中而不是不调用 onCreateOptionsMenu 来解决问题。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    boolean refreshVisible;

    if (refreshItem != null && refreshItem.isVisible()){//is being displayed prior to inflation
        refreshVisible = true;
    }else if (refreshItem == null){//it's null so the menu has never been created
        refreshVisible = true;
    }else {//it's not null and invisibe, other icon was being displayed
        refreshVisible = false;
    }

    menu.clear();//clear menu so there are no duplicate or overlapping icons
    getMenuInflater().inflate(R.menu.main, menu);//inflate menu
    refreshItem = menu.findItem(R.id.refresh);
    useDataItem = menu.findItem(R.id.use_data);
    refreshItem.setVisible(refreshVisible);//if menu is being created for first time or item was previously visible, then display this item
    useDataItem.setVisible(!refreshVisible);//display this item if not displaying other

    return true;

}