In my Activity I setup the NavController in OnCreate:
navController = findNavController(this, R.id.NavHostFragment)
In my Fragments, I setup the NavController in onViewCreated:
navController = Navigation.findNavController(view)
The Activity only navigates to a few Fragments (e.g. SitesFragment, ContactsFragment, TasksFragment etc) from the NavigationView when item is clicked as below:
R.id.nav_sites_fragment -> {
navController.popBackStack(R.id.sitesFragment, true)
navController.navigate(R.id.sitesFragment)
}
In the Fragments, click events (in RecyclerViews mainly heading to other Fragments, such as SiteFragment, ContactFragment, TaskFragment etc) are handled as below:
if (!navController.popBackStack(R.id.siteFragment, false)) {
// not in BackStack
navController.navigate(R.id.action_contactFragment_to_siteFragment)
}
The problem is, Fragments from Fragment actions remain in the backstack even when I popBackStack in the Activity actions..
I think my understanding of backstack is not correct as I'm not sure what is going on - but that maybe I have created two separate instances of NavController?
EDIT: Although I have looked at this post How to clear navigation Stack after navigating to another fragment in Android, I am still finding same behaviour. PopBackStack in Activity is not clearing Fragments added to the backstack..
For example:
SITES -> SITE -> CONTACT -> CONTACTS should remove first three fragments, but backpress still returns to CONTACT..