Search code examples
androidandroid-activityandroid-menu

How to hide menu on fragment (which is being replaced from the layout)?


I have checked and tried out all the possible codes here but those didn't work for me as i am replacing the layout only not having different toolbar.I am using fragments and NavigationDrawer, the navigationdrawer has listview, when a listitem is clicked it is replacing the layout with the following fragments. But how do i hide the menu or modify it based on different layout appeard?


Solution

  • If you want to control the option menu from Fragment you need to call setHasOptionsMenu in the onCreate of the Fragment:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    

    Then you can add, remove or clear the menu overriding onCreateOptionsMenu. For example this code remove every item in options menu:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
    }