我有如下的botton导航设置,它可以正常工作。
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)
现在,如果当前片段是第二个,并且其中设置了一些标志,我想防止切换片段
我尝试过使用bottomNavView.setOnItemSelectedListener
,但它破坏了整个导航控制器机制,需要自己进行片段和标题切换。
有没有其他方法可以覆盖一个特殊项目的导航控制器行为,并让它像往常一样用super.onItemSelected()
之类的东西处理其余的事情?
根据setupWithNavController()
文档:
当选择菜单项时,这将调用
onNavDestinationSelected
。
因此,如果您想从自己的侦听器执行默认行为,您可以简单地调用该方法。
// 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
)
}
}
您可以在navController中使用addOnDestinationChangedListener((,然后将当前目的地与片段id 进行比较
navController.addOnDestinationChangedListener { _, _, _ ->
if (navController.currentDestination?.id == R.id.fragment_id) {
}
else {
}
}