gpt4 book ai didi

android - Navigation.findNavController(it) 和 NavHostFragment.findNavController() 有什么区别?

转载 作者:行者123 更新时间:2023-12-05 00:20:00 24 4
gpt4 key购买 nike

我想知道 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 ,它会在 View 层次结构中向上查找 NavController。这适用于 onClick() 监听器或您正在与由 Fragment 目标创建的 View 交互的其他情况。

如果您有对 Activity 的引用和导航主机的 ID,请使用 Navigation.findNavController(Activity, @IdRes int)。根据 its Javadoc ,“这是一个围绕 Navigation.findNavController(View) 的便利包装器” - 它只是为您调用 findViewById()

当您有对 Fragment 的引用时,您可以使用 NavHostFragment.findNavController()。根据 its Javadoc ,它沿着 Fragment 层次结构向上移动(即调用 getParentFragment() 直到找到 NavHostFragment)调用之前通过 Navigation.findNavController(View)

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

关于android - Navigation.findNavController(it) 和 NavHostFragment.findNavController() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61553396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com