简体   繁体   English

仅在显示片段时显示导航抽屉菜单项

[英]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.

相关问题 导航抽屉-用于片段和子片段的操作栏的“隐藏和显示”菜单项? - Navigation Drawer - Hide and Show menu item of action bar for fragment and sub fragment? 如何显示带有导航抽屉菜单项的指示器 - How to show an indicator with a navigation drawer menu item 如何将片段添加到导航抽屉菜单项片段 - how to add a fragment to the navigation drawer menu item fragment 从导航抽屉中选择带有一些片段的滑动选项卡菜单项 - Selecting item of sliding tabs menu from navigation drawer with some fragment 单击导航抽屉中的菜单项时未显示片段 - Fragment is not getting displayed on clicking the menu item in Navigation Drawer 未显示片段中的菜单项 - Menu item in fragment not shown 固定顶部标题徽标并且滚动菜单项并显示在类别标题中时,如何创建左侧导航抽屉? - How to create left navigation drawer when top header logo is fixed and menu item is scrolling and show in category title? 拥有导航抽屉时在操作栏中显示菜单项图标 - Show menu item icons in actionbar while having navigation drawer 选择导航抽屉项目时无法显示片段 - Fragment can not be displayed when navigation drawer item is selected 单击消耗性菜单项时关闭导航抽屉的问题 - Issue in closing navigation drawer when click on Expendable menu item
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM