10

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

Pierre
  • 450
  • 6
  • 18

4 Answers4

7

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) 
Ainege
  • 219
  • 3
  • 8
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

goemic
  • 1,092
  • 12
  • 24
  • Thanks, the problem with this solution is that if I press back I lost the fragment (and I don't want it) – Pierre May 04 '22 at 15:42
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.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
pearleye
  • 29
  • 4
  • 3
    Please use a comment for the non-answering part I deleted. – Yunnosch Jul 09 '22 at 05:33
  • 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). – tacoshy Jul 09 '22 at 20:18
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32207737) – Junaid Khalid Jul 15 '22 at 09:29
-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)
         }