检查 NavDestination 是否代表 DialogFragment

Check if NavDestination represents a DialogFragment

我有一个 Activity 布局围绕 CoordinatorLayout 中的片段容器。切换目的地时,我想隐藏 FAB 并关闭 SnackBar(如果当前显示其中一个),并让目标 Fragment 在其 onViewCreated() 中需要时重新显示 FAB。这与 Material 设计指南一致,即当您切换目的地时,FAB 应该明显消失并重新出现。

所以我这样做了:

navController.addOnDestinationChangedListener { _, navDestination, _ ->
    binding.floatingActionButton.apply {
        hide()
        setOnClickListener(null)
    }
    currentSnackbar?.dismiss()
    //...
}

但是,当 DialogFragment 是导航目标时,前一个 Fragment 在返回时不会 onViewCreated() 再次调用,因为它从未离开过屏幕。

NavDestination 似乎没有任何方法来检查它是否代表 DialogFragment,即使 XML 区分 fragmentdialog

我知道我可以将显示代码的 FAB 移动到片段中的 onResume,但是在仅打开警报对话框时首先隐藏它看起来很愚蠢。我意识到我也可以创建一个父片段 class 将其隐藏在 onStop() 中,但我尽可能避免创建 class 层次结构层以使代码不那么脆弱(继承组合),而且我还想避免在整个应用程序中重复代码。

对话框目标实现 FloatingWindow interface:

A marker interface for NavDestination subclasses that float above the view of other destinations (i.e. DialogFragmentNavigator.Destination).

NavController.OnDestinationChangedListener instances can also customize their behavior based on whether the destination is a FloatingWindow.

因此您可以忽略使用 if (!(navDestination is FloatingWindow)) 导航到对话框。