Navigation.findNavController(it) 和 NavHostFragment.findNavController() 有什么不同?

use*_*604 2 android android-architecture-navigation

Navigation.findNavController(it)我想知道和之间的区别NavHostFragment.findNavController(this)。基本上两者都在做同样的事情,但不知道这些方法必须使用的确切位置。

ian*_*ake 6

根据导航到目的地文档

要检索片段、活动或视图的 NavController ,请使用以下方法之一

如果您只有对 a 的引用View,请使用Navigation.findNavController(). 根据其 Javadoc,它会沿着视图层次结构向上查找NavController. 这适用于onClick()侦听器或与目标创建的视图进行交互的其他情况Fragment

Activity如果您有对导航主机的 和 ID 的引用,请使用Navigation.findNavController(Activity, @IdRes int)。根据其 Javadoc,“这是一个方便的包装器Navigation.findNavController(View)”——它只需要findViewById()您。

当您有对 a 的引用时Fragment,可以使用NavHostFragment.findNavController(). 根据其 Javadoc ,它会在调用 to之前沿着层次结构向上走Fragment(即调用getParentFragment()直到找到 a NavHostFragment)。Navigation.findNavController(View)

在所有情况下,您都会得到相同的NavController回报,因此请使用方便的方式。