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
ToolbarinMainActivity.kt:
// setup Toolbar
val appBarConfiguration = AppBarConfiguration(navController.graph)
binding.mainToolbar.setupWithNavController(navController, appBarConfiguration)
Toolbarinmain_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
Fragmentthat 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?
I was able to do it with
inflateMenu:And clear it after navigation: