我有一个 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/