简体   繁体   中英

Android clear backstack when leaving item tab BottomNavigation

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

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

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.

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) 

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) }

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