Reputation: 299
Navgiation graph skeleton below:
MainActivity
|- RootNav
|- HomeNavGraph (RootNav's startDestination) (bottom nav tab 1)
|- HomeFragment (HomeNavGraph's startDestination)
|- ListFragment
|- SearchNavGraph (bottom nav tab 2)
|- SearchFragment (SearchNavGraph startDestination)
Below is the expected backstack:
| | | | |SearchFragment| | |
| | -> |ListFragment| -> | ListFragment | -> |ListFragment|
|HomeFragment| |HomeFragment| | HomeFragment | |HomeFragment|
Below is the actual backstack:
| | | | |SearchFragment| | |
| | -> |ListFragment| -> | ListFragment | -> | |
|HomeFragment| |HomeFragment| | HomeFragment | |HomeFragment|
Situation: When I click the back button on my device when SearchFragment
is active, the backstack pops both SearchFragment
and ListFragment
and shows HomeFragment
. However, when I click the bottom nav tab 1 then only SearchFragment
is poped and shows ListFragment
.
I tried using onBackPressedDispatcher
in my NavHostActivity like this:
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val currentDestination = navController.currentDestination
when (currentDestination?.id) {
R.id.navGraphSearchFragment -> {
navController.navigate(R.id.tabHomeFragment)
}
else -> {
if (!navController.popBackStack()) {
finish()
}
}
}
}
})
Realisation: While the nav_graph backstack is still active onBackPressedDispatcher
is never called.
Help: It would be helpful if anyone can explain how I can mimick the same navigation flow I get when I click the bottom nav tab with the device back button press.
Upvotes: 0
Views: 29