Search code examples
androidbottomnavigationviewandroid-architecture-navigation

Back navigation with bottom navigation view and navigation component


I have a bottom navigation view with 3 entry points (fragments A, B and C), and each of them can move to other fragments (A->D, B->E, C->F). To navigate, I am using the architecture navigation component. I want that when the user is in A, B or C and he presses the back button the app exits. If he is in D, E or F he should go to A, B or C respectively.

According to the documentation having the same ids in the menu and navigation graph is the way to set the view and navigation component up.

I know I can override the navigation and handle it myself to achieve what I want, or override the back button. But I would like to know if there is a way of achieving the desired behaviour without having to handle it manually (after all, that's the point of using the navigation component). Is there a way of doing this?

Also, is what I want to achieve the desired behaviour in material design with Android? It is my understanding that it is, but I could not find it in the material design documentation. I've tried several apps and I see different behaviours (twitter, maps and gmail don't exit the app, but tasks or keep do), so I suppose that both behaviours are acceptable.


Solution

  • The Principles of Navigation were specifically built by the Material and Android UX teams at Google as the way apps should be designed so as to prevent confusion on what the back button will do:

    This [start] destination is also the last screen the user sees when they return to the launcher after pressing the Back button.

    This ensures that users know that the back button won't kick them out of the app when on any other screen of your app. Conversely, that start destination serves as a sign post to the user that pressing the system back button will kick them back to the launcher.

    So it is absolutely expected that, when using the NavigationUI helpers, that you will always exit through the start destination of your graph (i.e., your A screen).

    Navigation has a separate concept, called top level destinations, which controls only whether the Up arrow on the app bar is displayed. This allows multiple top level destinations (such as your A, B, and C) to appear on the same hierarchical level from the user's point of view while still matching the system back Principles of exiting through the start destination.