Android Jetpack Navigation How to handle the Toolbar and BottomNavBar content

if you want to reach to another fragment by calling on menu item, you must give to item id the the same id which is in the destination id.

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return 
       item.onNavDestinationSelected(findNavController(R.id.nav_host_fragment))
            || super.onOptionsItemSelected(item)
}


<item android:id="@+id/dailyInfoFragment"
      android:title="@string/action_settings"
      android:orderInCategory="100"
      app:showAsAction="never"/>


    <fragment
        android:id="@+id/dailyInfoFragment"
        android:name="com.example.sonyadmin.infoPerDay.DailyInfoFragment"
        android:label="fragment_daily_info"
        tools:layout="@layout/fragment_daily_info"
        />

In your fragment:

NavController navHostFragment = NavHostFragment.findNavController(this);
NavigationUI.setupWithNavController(toolbar, navHostFragment);

enter image description here

When I click item on list item (Explore Fragment) it will negation to DetailFragment and when I click the back button on the toolbar it will return MainFragment.


Even though Alex's solution works, I would not recommend it for the purpose of managing the toolbar.

The toolbar should be part of your fragment's layout and each fragment should manage its own toolbar. you can inflate different menus for each fragment. even in the case of wanting to have the toolbar in the activity, I would recommend getting a reference to the toolbar form activity (through an interface) and then adding and manipulating its items in the fragment itself.

This would decouple your activity and fragment (which is one of the goals of having navigation graph and a router). a good rule of thumb is that imagine you want to remove the fragment, then you should not need to make any change to the activity.


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
    }

 }
}