Hide MenuItem in some Fragments
Asked Answered
P

18

73

I using menu drawer which has more Fragments. In some Fragments I have menu item REFRESH but in some fragments I want hide this menu item (I don't want show menu but I don't want hide ActionBar).

I try add override onCreateOptionsMenu() to Fragment where I don't want show this menu item but I can not get it to work. I try many way see commented line in code. Does any idea where is problem? And last this menu item go to hide when I activate menu drawer when is called onPrepareOptionsMenu() in MainActivity but I need do this when I'm in Fragment.

Fragment where I want hide menu item REFRESH:

 public class FindPeopleFragment extends Fragment {
    public FindPeopleFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
        //setHasOptionsMenu(false);
        return rootView;
    }

    private Menu menu=null;
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        inflater.inflate(R.menu.main, menu);
        this.menu=menu;
        menu.findItem(R.id.refresh).setVisible(false);
        getActivity().invalidateOptionsMenu();
        //setHasOptionsMenu(false);
        super.onCreateOptionsMenu(menu,inflater);
    }
}

MainActivity where is defined MENU DRAWER:

 //Slide menu item click listener
private class SlideMenuClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // display view for selected nav drawer item
        displayView(position);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.refresh:
            Toast.makeText(this, "Refreshing data...", Toast.LENGTH_SHORT).show();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

 // Called when invalidateOptionsMenu() is triggered
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.refresh).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}
Pornocracy answered 1/2, 2014 at 13:16 Comment(0)
M
54

In the Fragment where you don't want to show any menu options, you need setHasOptionsMenu(false); in the onCreate(), like this:

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

However, the menu that is being shown that you would like to hide (REFRESH), belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment level (and not show an Activity options menu), my suggestion is to delete the menu code from the Activity and implement it in your Fragment.

Activitys and Fragments can each have their own separate menus. See this link.

Monody answered 1/2, 2014 at 13:46 Comment(15)
Um no luck I try it but menu item is still there.( Problem will be else where.Pornocracy
You must set it in onCreate() not in onCreateView().Monody
yes I copy paste your code and as I say it dont work menu item is still visible.Pornocracy
If that didn't work then there's something going on with your code. The problem may lie else where.Monody
yes I know I dont have idea where can be another problem but thx a lot for your time and help.Pornocracy
Without seeing the rest of your code it'll be hard for me to help you further. Calling setHasOptionsMenu(false) in onCreate() should've done the trick. If that does not work, then there must be something in the application logic that's displaying the menu. You can post your code to a gist and share it...Monody
Ok I upload Fragment class and main activity class + menu xml files. dropbox.com/s/bbolxv2cuymfufj/MainActivity.txt dropbox.com/s/li20syi8qr177oo/Menu-main-xml.txt dropbox.com/s/w1zup8wnotabkkz/Fragment.txt and if you need full sources then I use this code because Im beginner in AND and I still learn how its works. androidhive.info/2013/11/…Pornocracy
OK. I see what the issue is. I will update my response shortly.Monody
@PavolFranek What did you change to get this to work? I'm having the same issue. I've removed the options menu from my FragmentActivity and only put it in one Fragment but it still shows up in all fragments.Fe
in my mainActivity I change return type from true to false because I m using menu drawer. So try push this to your mainAcivity>dropbox.com/s/hnaofotiez7btws/q1.txt I forgot remove if..its only for my code .)Pornocracy
@PavolFranek when i try to do like return type from true to false from main activity it causes my activity menu get disappear :(Vladikavkaz
yes because you dont create menu then. If you want hide only some item froms from menu use MenuItem item = menu.findItem(R.id.yourItem); item.setVisible(false); this add to onCreateOptionsMenuPornocracy
The solution of @pratham-kesarkar is much simpler and worked for meUtimer
My code used custom Toolbar and this did not help hide my menu items. The way that @pratham kesarkar mentioned below helps. https://mcmap.net/q/271843/-hide-menuitem-in-some-fragmentsCoffle
setHasOptionsMenu(true) is deprecated.Tan
G
230

In the fragment where you want to hide the Item

@Override
public void onPrepareOptionsMenu(Menu menu) {
    MenuItem item=menu.findItem(R.id.action_search);
    if(item!=null)
       item.setVisible(false);
}

and in onCreate() of your fragment

 setHasOptionsMenu(true);
Goring answered 14/1, 2016 at 20:32 Comment(1)
This is better than the accepted answer.Yonkers
M
54

In the Fragment where you don't want to show any menu options, you need setHasOptionsMenu(false); in the onCreate(), like this:

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

However, the menu that is being shown that you would like to hide (REFRESH), belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment level (and not show an Activity options menu), my suggestion is to delete the menu code from the Activity and implement it in your Fragment.

Activitys and Fragments can each have their own separate menus. See this link.

Monody answered 1/2, 2014 at 13:46 Comment(15)
Um no luck I try it but menu item is still there.( Problem will be else where.Pornocracy
You must set it in onCreate() not in onCreateView().Monody
yes I copy paste your code and as I say it dont work menu item is still visible.Pornocracy
If that didn't work then there's something going on with your code. The problem may lie else where.Monody
yes I know I dont have idea where can be another problem but thx a lot for your time and help.Pornocracy
Without seeing the rest of your code it'll be hard for me to help you further. Calling setHasOptionsMenu(false) in onCreate() should've done the trick. If that does not work, then there must be something in the application logic that's displaying the menu. You can post your code to a gist and share it...Monody
Ok I upload Fragment class and main activity class + menu xml files. dropbox.com/s/bbolxv2cuymfufj/MainActivity.txt dropbox.com/s/li20syi8qr177oo/Menu-main-xml.txt dropbox.com/s/w1zup8wnotabkkz/Fragment.txt and if you need full sources then I use this code because Im beginner in AND and I still learn how its works. androidhive.info/2013/11/…Pornocracy
OK. I see what the issue is. I will update my response shortly.Monody
@PavolFranek What did you change to get this to work? I'm having the same issue. I've removed the options menu from my FragmentActivity and only put it in one Fragment but it still shows up in all fragments.Fe
in my mainActivity I change return type from true to false because I m using menu drawer. So try push this to your mainAcivity>dropbox.com/s/hnaofotiez7btws/q1.txt I forgot remove if..its only for my code .)Pornocracy
@PavolFranek when i try to do like return type from true to false from main activity it causes my activity menu get disappear :(Vladikavkaz
yes because you dont create menu then. If you want hide only some item froms from menu use MenuItem item = menu.findItem(R.id.yourItem); item.setVisible(false); this add to onCreateOptionsMenuPornocracy
The solution of @pratham-kesarkar is much simpler and worked for meUtimer
My code used custom Toolbar and this did not help hide my menu items. The way that @pratham kesarkar mentioned below helps. https://mcmap.net/q/271843/-hide-menuitem-in-some-fragmentsCoffle
setHasOptionsMenu(true) is deprecated.Tan
S
42

please try this

@Override 
public void onPrepareOptionsMenu(Menu menu) {
    menu.clear();
}

and put this on your fragmen's onCreate()

setHasOptionsMenu(true);
Skilken answered 27/9, 2016 at 11:50 Comment(1)
This is a short answer.Disaffiliate
G
29

In Fragment Class

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

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
    }
Garzon answered 11/3, 2017 at 9:21 Comment(0)
F
15

in Kotlin for those who needs it

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setHasOptionsMenu(true)
}
override fun onPrepareOptionsMenu(menu: Menu) {
    super.onPrepareOptionsMenu(menu)
    menu.clear()
}
Fermata answered 4/8, 2020 at 7:26 Comment(1)
setHasOptionsMenu(true) is deprecated.Tan
N
11

I used the code below for hiding menu items in a fragment where I don't want to use it. Note: Please read comment

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    Fragment whichFragment=getVisibleFragment();//getVisible method return current visible fragment
    String shareVisible=whichFragment.getClass().toString();
    if(shareVisible.equals(AccFragment.class.toString())
            ||shareVisible.equals(SocFragment.class.toString())
            ||shareVisible.equals(DevFragment.class.toString())
            ){
        MenuItem item=menu.findItem(R.id.action_share);
        item.setVisible(false);
    }
    return super.onCreateOptionsMenu(menu);
}
Northerly answered 6/11, 2014 at 10:21 Comment(1)
Why not just use if (whichFragment instanceof AccFragment || whichFragment instanceof SocFragment || whichFragment instanceof DevFragment) { //your code } ?Kalasky
A
5

in Kotlin

override fun onPrepareOptionsMenu(menu: Menu) {
    val item: MenuItem = menu.findItem(R.id.action_search)
    item.isVisible = false
}

in onCreate() of your fragment setHasOptionsMenu(true)

Alkanet answered 23/6, 2020 at 12:20 Comment(1)
Perfect! If you want to hide a specific menu item this one will surely work.Trinhtrini
L
3

There are many different versions of similar solutions but unfortunately, none of them worked for me. I am sharing what eventually was useful for me to hide the whole overflow menu with multiple menu items. Thought maybe it's useful for anyone.

I grouped my menus with an id and then referred that id

@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.setGroupVisible(R.id.menu_overflow, false);
    super.onPrepareOptionsMenu(menu);
}

If you want to hide any individual menu item then you can use

menu.getItem(R.id.action_licenses).setVisible(false);

Important thing is that you should have setOptionsMenu(true) in onViewCreated()

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setHasOptionsMenu(true);
Licastro answered 14/5, 2017 at 18:56 Comment(0)
M
1

Call setHasOptionMenu(true) in onCreateView()

and Do not call super.onCreateOptionsMenu() in fragment's onCreateOptionMenu() instead call menu.clear() because this will override the existing menu with the activity's menu

This worked in my case.

Mcgray answered 1/2, 2020 at 11:14 Comment(0)
A
0

Or solve it in the same Fragment which created the menu, if you host the Actionbar on Activity level. This way you don't have to add it on every other Fragment where you don't want to show it:

public override void OnDestroy()
{
    base.OnDestroy();
    HasOptionsMenu = false;
}
Atticism answered 8/2, 2018 at 12:21 Comment(0)
N
0

Add these functions to your Fragment

  @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }
        @Override
        public void onPrepareOptionsMenu(Menu menu) {
            MenuItem item=menu.findItem(R.id.delete);
            item.setVisible(false);
        }
Nilla answered 27/3, 2019 at 5:18 Comment(0)
M
0

Firstly in your Activity that has the toolbar, create a method that sets up the overflow menu for you:

public void setUpOptionMenu(Toolbar toolbar){
    this.setSupportActionBar(toolbar);
}

In your fragments onCreateView() method, get the reference of your current activity and call your activities setUpOptionMenu() method:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    ...
    ...
    public void ((YourActivityName)this.getActivity()).setUpOptionMenu(null);
    ...
    ...
}

Cheers!!!

Manlove answered 19/11, 2019 at 18:30 Comment(0)
C
0

Overrride the following method just in your fragment and it will do the trick.

@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    // Do something that differs the Activity's menu here
    getActivity().getMenuInflater().inflate(R.menu.drawer, menu);
}
Channa answered 6/8, 2021 at 15:28 Comment(0)
P
0

2022 KOTLIN

On your activity, where you navigate to fragments, You can try like below, On below code, Tested on Side Navigation view, It has been shown wherever needed using toolbar.inflateMenu(R.menu.toolbar_menu) and hidden using toolbar.menu.clear() on toolbar reference.

binding.naviSideNav.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.side_nav_home->{
                toolbar.title=""
                toolbar.menu.clear()
                toolbar.inflateMenu(R.menu.toolbar_menu)
                toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.home_screen_bg))
                navController.navigate(R.id.navigation_home)
            }
            R.id.side_nav_appointments->{

            }
            R.id.side_nav_ehr->{

            }
            R.id.side_nav_invoices->{

            }
            R.id.side_nav_settings->{
                toolbar.title=getString(R.string.nav_menu_Settings)
                toolbar.menu.clear()
                toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.home_screen_bg))
                navController.navigate(R.id.navigation_settings)
            }
            R.id.side_nav_logout->{

            }
        }

        binding.dlt.closeDrawer(GravityCompat.START)
        true
    })
Pelvic answered 2/5, 2022 at 11:5 Comment(0)
E
0

Clean and redraw menu item

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        menu.clear()
        inflater.inflate(R.menu.main_menu, menu)
        menu.findItem(R.id.id_menu_search)?.isVisible = true
        super.onCreateOptionsMenu(menu, inflater)
    }
Elburr answered 2/11, 2022 at 14:38 Comment(0)
C
0

I have checked the answers but now the optionMenu has been deprecated in the latest Android api level

setHasOptionsMenu(false)

so for the people who are using MenuProvider for optionMenu can use the

setMenuVisibility(false)

like this in fragment

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setMenuVisibility(false)
    }
Centroclinal answered 25/1, 2023 at 7:17 Comment(3)
For some unknown reasons, this one didn't work for me. I'm using MenuProvider, and the menu options of the previous fragment are showing up on the current fragment. That shouldn't be happening.Immersed
Hi @EdwardQuixote, For every fragment u don't want to show the menu can add this method setMenuVisibility(false) in onCreateCentroclinal
This is not working, am I missing something?Oligarch
C
0

As many answers here are outdated because of framework deprecation. What worked for me as of today (2024-02-20) was:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        activity?.addMenuProvider(object : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menu.clear()
            }
            
            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                return true
            }
        })
    }

Of course, the override can happen per fragment needing to hide the menu, or, as in my case, I had only one fragment needing the menu so, I've added that in my BaseFragment from which all the Fragments descend, and added a specific implementation for the fragment needing the menu, like so:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
            
    activity?.addMenuProvider(object : MenuProvider {
        override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
    
            menu.clear() // <-- very important to not have the menu duplicated elsewhere
            
            menuInflater.inflate(R.menu.search_bar_menu, menu) // <-- inflate your specific menu
        }
    
        override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
            return true
        }
    })
}
Complain answered 20/2, 2024 at 13:20 Comment(0)
C
-1

Just find the item you want to hide using findItem then set its visibility to false.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    MenuItem item = menu.findItem(R.id.action_settings);
    item.setVisible(false);
}
Carlenacarlene answered 12/5, 2018 at 23:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.