I have a navigation drawer with different fragments. There is a default toolbar every Fragment
should use, except of one Fragment
which needs a collapsing Toolbar
.
How can I switch between the toolbars for the fragments ?
The recommend practice is to use toolbars in fragments instead of a common toolbar in activity. That way you can control the looks and behaviour of toolbar in fragment. Refer https://developer.android.com/guide/navigation/navigation-ui#support_app_bar_variations
I'm using Jetpack's Navigation components with single Activity and different Fragments in my app.
Some Fragments are accessible from bottom navigation (and have Toolbar
from Activity). Some others are "special" Fragments and have their own Collapsible Toolbar.
To achieve this, I'm hiding Toolbar from Activity in "special" Fragments with this code in Activity:
// Handle toolbar changes in different Fragments
val navController = findNavController(R.id.nav_host_fragment)
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.my_special_fragment_with_collapsible_toolbar -> {
binding.toolbarMain.visibility = View.GONE
}
else -> {
binding.toolbarMain.visibility = View.VISIBLE
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With