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

标签 android android-fragments android-actionbar android-menu fragmenttransaction

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

我不能使用 boolean 因为我仍然需要它在方向改变时重新膨胀。关于如何根据我的情况处理方向变化的任何建议?

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

最佳答案

我不是不调用 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;

}

关于android - 如何在调用 FragmentManager.replace() 时不调用 onCreateOptionsMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31927769/

相关文章:

android - 我需要有关 Widget 和 PendingIntents 的帮助

java - 使用 fragment 事务的 NullPointerException

Android ViewPager 在 TabLayout 之上显示 View

android - 首选项菜单中 Android 向上/向后导航的动态父 Activity

android - listview 作为 sherlock 操作栏中的操作溢出

java - android:如何从扩展 RecyclerView 的类更新徽章 TextView

java - 查找一个表中不存在另一表中存在的匹配列数据的记录

android - 如何解决android studio加载项目?无法加载项目 : java. lang.IllegalStateException: @NotNull 方法

Android:我写入 SD 卡的文件在 Windows 资源管理器中不显示,适用于 Acer Iconia Tab

java - 为什么方向改变后仍然显示该 fragment ?