Why optionsMenu does not show up in fragment?

40 Views Asked by At

I have an app with an Activity and multiple Fragments. I want all fragments to have one default Toolbar which is managed by NavigationUI, and show a Menu only for the first Fragment. Problem: the OptionsMenu doesn't show up.

  • This is how I setup my Toolbar in MainActivity.kt:
// setup Toolbar
val appBarConfiguration = AppBarConfiguration(navController.graph)
binding.mainToolbar.setupWithNavController(navController, appBarConfiguration)
  • Toolbar in main_activity.xml:
<androidx.appcompat.widget.Toolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:layout_marginTop="?attr/actionBarSize"/>
  • In the Fragment that I want an optionsMenu:
 setHasOptionsMenu(true)
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)
    inflater.inflate(R.menu.overflow_menu, menu)
}

I tried doing it with two Toolbars, but it doesn't seem a good practice.

How can I achieve this effect with one toolbar?

1

There are 1 best solutions below

1
arzhang On

I was able to do it with inflateMenu:

val toolbar = activity?.findViewById<Toolbar>(R.id.main_toolbar)
toolbar?.inflateMenu(R.menu.overflow_menu)

And clear it after navigation:

binding.navBtn.setOnClickListener {
    navController.navigate(R.id.action_startFragment_to_secondFragment)
    toolbar.menu.clear()
}