底部导航 setOnItemSelectedListener 返回 super

yau*_*nka 4 android kotlin

我的按钮导航设置如下,它工作正常。

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)
Run Code Online (Sandbox Code Playgroud)

现在,如果当前片段是第二个片段并且其中设置了一些标志,我想阻止切换片段。

我尝试过使用,bottomNavView.setOnItemSelectedListener但它破坏了整个导航控制器机制,并且需要您自己进行片段和标题切换。

是否有其他方法可以覆盖特定项目的导航控制器行为并让它像往常一样处理其余部分,例如super.onItemSelected()

ian*_*ake 6

根据文档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
        )
    }
}
Run Code Online (Sandbox Code Playgroud)