I have botton navation setup up as below and it works all right.
navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(setOf(R.id.nav_1, R.id.nav_2))
setupActionBarWithNavController(navController, appBarConfiguration)
binding.bottomNavView.setupWithNavController(navController)
Now I would like to prevent switching fragments if current fragment is the second one and it has some flag set in it.
I've tried using bottomNavView.setOnItemSelectedListener
but it breaks the entire nav controller mechanism and requires doing fragment and title swithcing by yourself.
Is there any other way of overriding nav controller behaviour for a pariticular item and let it handle the rest as usual with something like super.onItemSelected()
?
As per the setupWithNavController()
documentation:
This will call
onNavDestinationSelected
when a menu item is selected.
So you can simply call that method if you want to do the default behavior from your own listener.
// Call setupWithNavController to get the automatic
// selection of the correct bottom nav item
// based on the NavController's state
binding.bottomNavView.setupWithNavController(navController)
// Then override the OnItemSelectedListener
// with your own with your custom logic
binding.bottomNavView.setOnItemSelectedListener { item ->
if (navController.currentDestination?.id == R.id.fragment_id && !yourConditionIsMet) {
// Return false to not allow navigating to the tab
false
} else {
// Do the default behavior
onNavDestinationSelected(
item,
navController
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With