I am implementing an android app (in Kotlin, but that is not relevant to the Problem) in my free time and I try to use android jetpack and new libraries. I have a single Act
I made simple example for this issue. https://github.com/isaul32/android-sunflower
Create set of top level destinations at first
val topLevelDestinations = setOf(R.id.garden_fragment,
R.id.plant_list_fragment)
appBarConfiguration = AppBarConfiguration.Builder(topLevelDestinations)
.setDrawerLayout(drawerLayout)
.build()
and then override onSupportNavigateUp function like this
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController, appBarConfiguration)
}
You don't have to override AppBarConfiguration. Since version alpha7
AppBarConfiguration has a constructor with a set of ids for all top level destinations.
Set<Integer> topLevelDestinations = new HashSet<>();
topLevelDestinations.add(R.id.fragment1);
topLevelDestinations.add(R.id.fragment2);
appBarConfiguration = new AppBarConfiguration.Builder(topLevelDestinations)
.setDrawerLayout(drawerLayout)
.build();
NavigationUI.setupActionBarWithNavController(this,
this.navController,
this.appBarConfiguration);
This is not default as the navigation graph has only a single start fragment which should always be the single entry point of the application.
Editing the default behavior with AppBarConfiguration does not make it behave as before, every top level fragment is placed on the back stack so back button will go to all top level fragments. It is unclear how I can make top level fragments as the first element of the back stack.
To get a correct behavior of toolbar and drawer with multiple top level destinations, you can use following code:
val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
/*
Create AppBarConfiguration with set of top level destinations and drawerLayout
Set contains ids of your navigation graph screens
*/
val appBarConfiguration = AppBarConfiguration(
setOf(R.id.defaultFragment, R.id.firstFragment, R.id.secondFragment),
drawer_layout
)
//finally configure toolbar
toolbar.setupWithNavController(navController, appBarConfiguration)
This code will ensure that hamburger icon is displayed on all of your top level destinations, and back button will appear when you navigate deeper.
Read more here
setOf and setDrawerLayout are depricated you should use
AppBarConfiguration configuration = new AppBarConfiguration.Builder(R.id.defaultFragment, R.id.firstFragment,R.id.secondFragment).setOpenableLayout(drawerLayout).build();