Navigation Controller (Managing Backstack) Jetpack Android

Good day. So I’ve been working around with NavComponent of Jetpack for Android

I’ve thought that management of BackStack of fragments had to be implemented there already, well in fact it is there but I have faced an issue.

Here is my structure:

I have and entry Activity

I have a NavHost in the activity

I have Bottom Navigation bar in the Activity

For each Bottom Item I am using separate Fragments to navigate through.

Here is the code for the navigation.

     bottomNavigationView.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.navigation_home -> {
                navController.apply {
                    navigate(R.id.navigation_home)
                }
                true
            }
            R.id.navigation_dashboard -> {
                navController.apply {
                    navigate(R.id.dashboardFragment)
                }
                true
            }
            R.id.navigation_notifications -> {
                true
            }
            else -> {
                false
            }
        }
    }

Never mind the last item.

So the issue is next.

If I try to switch between home and dashboard multiple times, when I press back then the stack surely will start popping all the items included there. So if I move like 6 times it will take me 12 attempts to actually exit the app.

Currently I couldn’t find any source where for example the navigate() method will accept some sort of argument to cash my fragments instead of recreating it each time and adding to the BackStack.

So what kind of approach would you suggest?

If I to manage the BackStack manually on each back button pressed, what’s the purpose of NavController at all? Just for creating and FORWARD navigation?

I think I’m missing some source in Android’s official docs.

Thank you beforehand.

P.S.
using navController.popBackStack() before calling navigate() surely isn’t the correct choice.

Source: Android Questions

LEAVE A COMMENT