[英]Show navigation drawer menu item only when a Fragment is shown
I am trying to show a button in the actionbar when a Fragment is shown and to hide the button when the other Fragment are shown. 我试图在显示片段时在操作栏中显示按钮,并在显示其他片段时隐藏按钮。
I Override the onCreateOptionsMenu
method: 我重写
onCreateOptionsMenu
方法:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
MenuItem item= menu.findItem(R.id.action_example);
item.setVisible(true);
super.onCreateOptionsMenu(menu,inflater);
}
And use setHasOptionMenu(true)
: 并使用
setHasOptionMenu(true)
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
I have done a test and I noticed that initially the button doesn't appear in the other Fragment , but after I open the Fragment in which I put this code above, the button is shown also in the other Fragment. 我进行了测试,发现按钮最初没有出现在另一个Fragment中,但是在打开将代码放在上面的Fragment之后,按钮也显示在另一个Fragment中。
What you are missing is removing the optionsMenu in the onDestroy of the fragment. 您缺少的是删除片段的onDestroy中的optionsMenu。 The behaviour you describe is logical with your code: when the Fragment is created you also create the options menu.
您描述的行为与代码是合乎逻辑的:创建片段时,您还会创建选项菜单。 It will not automatically be destroyed when the Fragment is destroyed.
当片段被销毁时,它不会自动销毁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.