Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing Toolbar only for one Fragment in Navigation View

The Problem

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.

My Question

How can I switch between the toolbars for the fragments ?

like image 501
Mayr Technologies Avatar asked Jun 23 '17 12:06

Mayr Technologies


2 Answers

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

like image 197
Vasudev Avatar answered Oct 12 '22 11:10

Vasudev


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
        }
    }
}
like image 23
Micer Avatar answered Oct 12 '22 11:10

Micer