Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have different menus in a Toolbar for different fragments?

I have a project using Drawer and Swipe tabs that I created using this tutorial. I'm using the support library to make Material Design available for older android versions. I'm also using ToolBar instead of ActionBar. I have a menu attatched to that ToolBar:

    toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    toolbar.inflateMenu(R.menu.menu_main);

What I'm struggling with is having specific menus for each fragment. I tried many answers to other similar questions, like this and this to no avail. Most people are suggesting the implementation of these methods but they only seem to work for ActionBar and in my case I have a android.support.v7.widget.Toolbar.

I also tried using

toolbar.getMenu().findItem(R.id.menuitem).setVisible(false);
supportInvalidateOptionsMenu();

But it also does not work. In this case, my menu just disappears.

I've been searching and struggling with this for weeks to to avail. Am I doing something wrong?

How can I have specific menus for each fragment? I think that hiding menu items may be the easier choice to achieve that, but if you guys have any other way of accomplishing that, I would be grateful.

like image 372
Anderson Madeira Avatar asked Dec 20 '25 21:12

Anderson Madeira


1 Answers

You should call setSupportActionBar(toolbar) when you setup your Toolbar (probably in onCreate) and inflate your menu as usual in onCreateOptionsMenu(Menu menu) method. In this method you can handle the different Menus, whether it's by hiding the items or just inflating a different menu based on the fragment.

Then, as you said, call supportInvalidateOptionsMenu(); when you change between fragments to recreate the Menu.

like image 167
Daniel Ocampo Avatar answered Dec 23 '25 11:12

Daniel Ocampo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!