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

How to avoid the up button with jetpack navigation and bottom tabs?


I would like to have a behavior similar to YouTube:

  • have a toolbar and bottom tabs
  • going to "Library" (5th tab), the up button doesn't appear
  • going inside "My Videos", the up button appears

Here are my constraints:

  • use jetpack navigation
  • use a Toolbar (inside an AppBarLayout if that matters)
  • have bottom tabs (BottomNavigationView)
  • all bottom tabs are "top level" in the sense where they don't change the Toolbar up button
  • other application screens are not "top level" and should have an up arrow
  • one of the tabs is the navigation graph's default destination

By default, when all is implemented, the navigation is handled automatically by the Jetpack Navigation library. I hook the toolbar with the navigation controller using this helper:

NavigationUI.setupWithNavController(main_toolbar, navController)

This works well, but if I switch one of the bottom tabs, the up button appears and pressing it pops back to the default destination.

This is fine when bottom tabs are not used, but this is awkward when they are.


Solution

  • You can specify AppBarConfiguration as a third param for NavigationUI.setupWithNavController. And pass top level destinations to it, like this:

    Set<Integer> topLevelDestinations = new HashSet<>();
    topLevelDestinations.add(R.id.navigation_home);
    topLevelDestinations.add(R.id.navigation_trending);
    topLevelDestinations.add(R.id.navigation_subscriptions);
    topLevelDestinations.add(R.id.navigation_inbox);
    topLevelDestinations.add(R.id.navigation_library);
    
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration
            .Builder(topLevelDestinations)
            .build();
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
    

    More details: AppBarConfiguration