简体   繁体   中英

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:

@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) :

@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.

What you are missing is removing the optionsMenu in the onDestroy of the fragment. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM