Check if NavDestination represents a DialogFragment

Ten*_*r04 1 android android-architecture-navigation

I have an Activity layout that surrounds the fragment container in a CoordinatorLayout. When switching destinations, I want to hide the FAB and dismiss the SnackBar if either is currently displayed, and let the destination Fragment reshow the FAB if it needs to in its onViewCreated(). This is consistent with the Material Design guidelines that say the FAB should visibly disappear and reappear when you switch destinations.

So I did this:

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

However, when a DialogFragment is the navigation destination, the previous Fragment will not have onViewCreated() called again when navigating back, because it never left the screen.

NavDestination doesn't seem to have any way to inspect whether it represents a DialogFragment, even though the XML distinguishes between fragment and dialog.

I realize I could move the FAB showing code to onResume in the fragment, but it would look silly to hide it in the first place when only opening an alert dialog. I realize I could also create a parent Fragment class that hides it in onStop(), but I try to avoid creating class hierarchy layers when possible to make code less fragile (composition over inheritance), and I also want to avoid repeating the code all over the app.

ian*_*ake 5

对话目标实现FloatingWindow接口

NavDestination浮动在其他目的地(即DialogFragmentNavigator.Destination)视图上方的子类的标记接口。

NavController.OnDestinationChangedListener实例还可以根据目标是否为FloatingWindow.

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