"by navArgs<ScoreFragmentArgs>()" 和 "ScoreFragmentArgs.fromBundle(arguments!!)" 有什么区别

What is the difference between "by navArgs<ScoreFragmentArgs>()" vs "ScoreFragmentArgs.fromBundle(arguments!!)"

val scoreFragmentArgs1 by navArgs<ScoreFragmentArgs>() 

val scoreFragmentArgs2 = ScoreFragmentArgs.fromBundle(arguments!!)

我能够使用上述任何语句访问从前一个片段传递的参数。有人可以解释差异以及何时使用它们。提前致谢

第二个调用比较简单。每当该行运行时,都会急切地评估它,因此它将要求 arguments 包已经就位,并包含您希望包含在其中的所有键。


第一种方法为您提供了一个延迟创建的 Args 实例,它只会在您第一次尝试读取其值时被初始化。因此,在 class 级别声明它是安全的。有关所有详细信息,请参阅文档中的 navArgs。最重要的部分:

It is strongly recommended that this method only be used when the Activity is started by androidx.navigation.NavController.navigate with the corresponding androidx.navigation.NavDirections object, which ensures that the required arguments are present.

This property can be accessed only after the Activity is attached to the Application, and access prior to that will result in IllegalStateException.