StefMa
StefMa

Reputation: 3434

Navigation should pop back stack instead of returning to start destination

My Activity has a NavHostFragment and a BottomNavigationView in its layout. The NavHostFragment has a main_navigation_graph which contains four Fragments in it. Their ids matching the BottomNavigationView#menu so that the Navigation can handle all the stuff by itself when I call

activity_main_bottom_navigation.setupWithNavController(navController)

Everything works so far. My problem is that the back button will go to the start destination when another tab (in the BottomBar) was selected.

I know that is the intended behaviour (at least according to the NavigationUI.onNavDestinationSelected documentation):

...

By default, the back stack will be popped back to the navigation graph's start destination. Menu items that have android:menuCategory="secondary" will not pop the back stack.

But that isn't what I want 🙃.

I want the behaviour like

If the user is at the "root" of a tab (from the BottomNavigation) and the user presses back -> close the App (finish the Activity).

How can I achieve that?

This gif demonstrates the current implementation:

When I at the Szenen tab and press back I want to close the Activity. Instead it goes to the startDestination (which is the System tab).

Upvotes: 3

Views: 4467

Answers (3)

Siarhei Yartsau
Siarhei Yartsau

Reputation: 11

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
    if (item.itemId != host.navController.currentDestination?.id) {
        host.navController.navigate(
            item.itemId, null,
            NavOptions.Builder().setPopUpTo(R.id.nav_graph_main, false).build()
        )
    }
    return true
}

In use:

binding.bottomBar.setOnNavigationItemSelectedListener(this)

Upvotes: 1

Sheraz Hussain Turi
Sheraz Hussain Turi

Reputation: 47

In the action of navigating from startDestination (System in your app) to another fragment (sneez in your app) from where you want to close the app. Just add the below two lines in action of startDestination to another fragment in navigation graph.

app:popUpTo="@id/homeFragment"
app:popUpToInclusive="true"

It worked for me.

Note: If you want to close the app from other fragment instead of startDestination

Upvotes: 0

ianhanniballake
ianhanniballake

Reputation: 199815

setupWithNavController follows the Principles of Navigation. If you want to deviate from the Principles of Navigation, you'll need to write your own OnNavigationItemSelectedListener for your BottomNavigationView that does what you want.

Upvotes: 1

Related Questions