如何防止 BottomNavigationView(即使用导航组件设置)更改项目单击的目的地

How to prevent BottomNavigationView (that is setup with Navigation Component) from changing destinations an item click

我有一个带有导航组件的 BottomNavigationView 设置,我想拦截在按下某个项目时更改目的地的处理,并防止它在特定条件下更改目的地。

例如:如果用户正在导航到目的地但他没有登录,则显示一个对话框。

我该怎么做?

我似乎找不到可以调用 OnDestinationChange 并返回某种布尔值以通知导航组件它是否应该继续导航的侦听器。

使用导航组件方法无法做到这一点,但有一个不会中断导航流程的简单解决方法。 在你的底部导航视图上获取菜单并设置 onItemClickListener 和 return true 如果你不希望导航组件接收点击因此没有导航发生 这是例子

binding.bottomNav.menu.findItem(R.id.searchFragment)?.setOnMenuItemClickListener {
            if(viewModel.isUserAuthorized()) {
                false // here this will allow navigation component to consume the click
            }
            else {
                 showUnauthorizedUserDialog()
                 true // here this will prevent navigation component from consuming the click
            }
}

另外根据 onMenuItemClick

的文档

@return Return true to consume this click and prevent others from executing.