Navigation graph with multiple top level destinations

情到浓时终转凉″ 提交于 2019-11-30 13:01:13

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.

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)
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!