Android clear backstack when leaving item tab BottomNavigation

1.8k Views Asked by At

I am using the last navigation library (version 2.4.0) which include multiple backstacks with a bottom navigation view.

The default behavior is that each backstack is saved when user go back to a tab. I want to clear a backstack when the user leave a tab.

Based on this bottom nav with 3 tabs :

Tab1 Tab2 Tab3
ScreenA1 ScreenB1 ScreenC1
ScreenA2 ScreenB2 ScreenC2

From Tab1, if user:

  • go to ScreenA2
  • clic on Tab2 (ScreenB1 displayed)
  • go back to Tab1
  • here I want ScreenA1 and not ScreenA2 (default behavior of navigation library)

Thanks

4

There are 4 best solutions below

1
Dinesh Radhakrishnan On

I just done by onNavigationItemSelected Listener

  1. The id in your navigation.xml and menu.xml should be different

  2. When you handle the click action for particular item, try this

             R.id.home_bottom_item -> {navController.popBackStack();
             navController.navigate(R.id.home_bottom_item)
         }
    
1
Khaled Abdelnabi On

In your navigation file add these properties app:popUpTo and app:popUpToInclusive to the action which navigates to ScreenA2.

<action
    android:id="@+id/action_A1_to_A2"
    app:destination="@id/A2"
    app:popUpTo="@+id/A1"
    app:popUpToInclusive="true"/>

for more information look at this link: popUpTo example: circular logic

3
pearleye On

Try invoking the below before you invoke the method to navigate to TAB1.

navController.popBackStack(R.id.ScreenA1, false);

This worked for me wherein I had a similar scenario to you.

1
Ainege On

You can turn off multiple backstacks for tabs, as it was before lib version 2.4. For this you should change

navView.setupWithNavController(navController) 

to

NavigationUI.setupWithNavController(navView, navController, false)