Anderson Madeira
Anderson Madeira

Reputation: 430

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.

Upvotes: 3

Views: 626

Answers (1)

Daniel Ocampo
Daniel Ocampo

Reputation: 256

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.

Upvotes: 2

Related Questions