Search code examples
androidandroid-fragmentsandroid-toolbar

How can I change menu items in top bar in different fragments?


I use MaterialToolBar for showing TopAppBar. I have three fragments, when showing each of them, I want to show different items in the top menu. How to do it?


Solution

  • instead of toolbar.setOnMenuItemClickListener you need to use this :

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.game_menu, menu);
        return true;
    }
    

    For more info please have a look at this answer.

    A quick overview you need to inflate different menu resource everytime you need to change your menu. Also you need to set OnOptionsItemSelected for the custom actions you need to perform.

    You might also need to add this for fragment setHasOptionsMenu(true); in your onCreate method.