Search code examples
androidandroid-architecture-componentsandroid-jetpackandroid-architecture-navigation

Android Jetpack Navigation How to handle the Toolbar and BottomNavBar content


I am a bit confused on how the Navigation component fits in the app behavior. It all looks nice and shiny in tutorials where you don't do things too complex but when implementing in real app, things seem different.

Before Navigation

Before implementing navigation I had to manually run fragment transactions. In order to do this, my fragment would implement an interface onFragmentAction which passed a bundle to the main Activity and in the activity based on the actions, replace the current fragment with another one.

The second part that needs handling is the top toolbar and the BottomAppBar. For instance BottomAppBar needs to have the FAB aligned differently on some fragments or hidden in others. Also the top ToolBar needs to be expanded on some or collapsed on others. To do this, I listened to FragmentManager.OnBackStackChangedListener and based on the fragment tag getSupportFragmentManager().getBackStackEntryAt(size - 1).getName() change the layout accordingly.

With Navigation

The first part seems to be easy to do: pass params and start new fragments. But I have no idea if navigation can handle the toolbars management or I need to keep managing it from my Activity.


Solution

  • The toolbar title is set based on 'label' value inside navigation graph, if you want to do something different with toolbar or BottomAppBar you can add addOnNavigatedListener inside your activity, and based on current destination do something.

    findNavController(nav_host_fragment).addOnNavigatedListener { controller, 
     destination ->
     when(destination.id) {
        R.id.destination1 -> {
            //Do something with your toolbar or BottomAppBar
        }
        R.id.destination2 -> {
            //Do something with your toolbar or BottomAppBar
        }
    
     }
    }