Android clear backstack when leaving item tab BottomNavigation
E

4

9

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

Englishism answered 2/2, 2022 at 22:8 Comment(0)
P
8

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) 
Pitzer answered 22/7, 2022 at 7:41 Comment(1)
Saved me after decades of pure agony. No sure why this is not the top answer.Nembutal
M
0

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

Mccoy answered 28/3, 2022 at 22:29 Comment(1)
Thanks, the problem with this solution is that if I press back I lost the fragment (and I don't want it)Englishism
E
0

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.

Estrone answered 9/7, 2022 at 5:27 Comment(3)
Please use a comment for the non-answering part I deleted.Polymerization
Please also remind that using other options as a workaround to your account limitation is not allowed. You will unlock the comment option at 50 reputations).Remex
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewBreda
T
-1

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)
         }
    
Turn answered 14/2, 2022 at 17:54 Comment(1)
Thanks but this is not working.Englishism

© 2022 - 2024 — McMap. All rights reserved.