Search code examples
androidkotlinnavigation-drawerandroid-toolbar

Android: How to override navigation drawer toolbar menu in a Fragment


I'm creating an application with a navigation drawer and I need to edit his toolbar where I'm in a specific fragment.

I've tried to inflate it by overriding the 'onCreateOptionsMenu' function in my fragment class:

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.menu_activity_main, menu)
    super.onCreateOptionsMenu(menu, inflater)
}

I expect to have "menu_activity_main" menu overridden on the action bar menu but it's not.

It currently looks like this: https://prnt.sc/p32sj5

But I want this menu instead: https://prnt.sc/p32tp4


Solution

  • This is probably because you didn't call the setHasOptionMenu(Boolean) method in your Fragment class (as what the notes of the onCreateOptionsMenu method specify you're supposed to).

    This should be placed ideally in your onCreate lifecycle hook:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionMenu(true)
        // ...
    }