https://kotlinlang.org logo
#android
Title
# android
c

Cyberpunk Keanu

11/15/2019, 10:41 AM
Hey all. I have a bottom navigation with 5 tabs But I'm using 6 Fragments. The first one is displayed by default when the activity is loaded. Then the rest 5 fragments are assigned to the 5 tabs in my bottom navigation. Now here is my ideal scenario. 1st Fragment always stays in the back stack. Then even if you keep switching between the 5 tabs, on back pressed should go to the 1st default fragment. However, idk how to do it & hence a result I now have a backstack of all the tabs that I switched in between. Anyone idea how to handle this back stack? I just want to go to the 1st Fragment on back/up press & not into a never ending backstack of tabs I switched.
c

Christiano

11/15/2019, 10:58 AM
You could try to override your onBackPressed() to return to the first fragment in the backstack? 🤔
c

Cyberpunk Keanu

11/15/2019, 11:03 AM
I thought about that but that doesn't solve the back stack problem. If I press back even after I've returned to the first fragment, It'd navigate to the fragment behind it in the back stack.
c

Christiano

11/15/2019, 11:10 AM
Hmm, it’s a bit hacky-ish, but you could get the first fragment from the backstack, clear the backstack completely, and then add only that fragment back to the backstack 😅
g

gvetri

11/15/2019, 11:41 AM
If you’re using the Navigation component maybe you can implement some logic using the OnDestinationChangedListener. https://developer.android.com/guide/navigation/navigation-ui#listen_for_navigation_events