Navigation.findNavController(it) 和 NavHostFragment.findNavController() 有什么区别?
What is the different between Navigation.findNavController(it) and NavHostFragment.findNavController()?
我想知道 Navigation.findNavController(it)
和 NavHostFragment.findNavController(this)
之间的区别。基本上两者都在做同样的事情,但不知道这些方法必须使用的确切位置。
根据 Navigate to a destination documentation:
To retrieve the NavController for a fragment, activity, or view, use one of the following methods
如果您只有 View
的引用,请使用 Navigation.findNavController()
。根据 its Javadoc,它会在视图层次结构中向上查找 NavController
。这适用于 onClick()
听众或您正在与由 Fragment
目的地创建的视图交互的其他情况。
如果您有对 Activity
和导航主机 ID 的引用,请使用 Navigation.findNavController(Activity, @IdRes int)
。根据 its Javadoc、"this is a convenience wrapper around Navigation.findNavController(View)
" - 它只是为您调用 findViewById()
。
当您有对 Fragment
的引用时,您可以使用 NavHostFragment.findNavController()
。根据 its Javadoc,它沿着 Fragment
层次结构向上移动(即调用 getParentFragment()
直到找到 NavHostFragment
)before 调用至 Navigation.findNavController(View)
.
在所有情况下,您都会得到相同的 NavController
,所以请使用方便的任何东西。
我想知道 Navigation.findNavController(it)
和 NavHostFragment.findNavController(this)
之间的区别。基本上两者都在做同样的事情,但不知道这些方法必须使用的确切位置。
根据 Navigate to a destination documentation:
To retrieve the NavController for a fragment, activity, or view, use one of the following methods
如果您只有 View
的引用,请使用 Navigation.findNavController()
。根据 its Javadoc,它会在视图层次结构中向上查找 NavController
。这适用于 onClick()
听众或您正在与由 Fragment
目的地创建的视图交互的其他情况。
如果您有对 Activity
和导航主机 ID 的引用,请使用 Navigation.findNavController(Activity, @IdRes int)
。根据 its Javadoc、"this is a convenience wrapper around Navigation.findNavController(View)
" - 它只是为您调用 findViewById()
。
当您有对 Fragment
的引用时,您可以使用 NavHostFragment.findNavController()
。根据 its Javadoc,它沿着 Fragment
层次结构向上移动(即调用 getParentFragment()
直到找到 NavHostFragment
)before 调用至 Navigation.findNavController(View)
.
在所有情况下,您都会得到相同的 NavController
,所以请使用方便的任何东西。