简体   繁体   中英

Bottom Navigation Bar issue using Navigation Component

The default behavior of Bottom Nav View when pressing back button is that navigation returns to home fragment and pressing back again quits the application however, when the home fragment is not the root fragment in navigation the issues arise. Eg If login screen is before the main screen (which is with bottom nav view), after navigation to main screen, every tab navigation is placed in stack which is very weird. Even if you try to remove login screen in navigation graph using popUpTo and popUpToInclusive, nothing changes. Any suggestions?

every tab navigation is placed in stack which is very weird

This is a consequence of the setupWithNavController implementation. It's rather simple:

  • When an item is selected on the navigation bar:
    • Pop the current backstack up to, and excluding, the start destination of the navigation graph (1)
    • Navigate to the menu item's corresponding destination
  • When the NavController changes destination:
    • Identify the corresponding menu item, by matching the destination ID with a menu item's ID (which is also a destination's ID)
    • Simply set the identified item as selected

The navigation unexpectedly beginning to stack is a result of your backstack being out of sync with the expectations of the setupWithNavController implementation as per (1). Namely, if the start destination of the graph does not exist anywhere within your backstack, the current tab's backstack won't be popped up, resulting in tabs eventually having stacked on top of each other.

Hence, you should be fine so long as you make sure to always keep the start destination of your navigation graph somewhere reasonable within the backstack. With relation to your particular situation, it's also a good idea to have the default tab on your navigation bar as the start destination of the navigation graph that the navigation bar's set up NavController is using.

PS Google should've at least touched on this requirement within the documentation for setupWithNavController . I quite dislike magical black box implementations such as this one when there is a clear risk of misuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM