我正在尝试使用sharedViewModel
作为arguments
注入key
。
private val args: TrackDetailFragmentArgs by navArgs()
private val trackVM: TrackDetailViewModel by sharedViewModel(key = args.trackId.toString())
这是我得到的错误
Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.marcheoutdoor.fragments.TrackDetailFragment: calling Fragment constructor caused an exception
at androidx.fragment.app.Fragment.instantiate(Fragment.java:474)
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:165)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:181)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:50)
at androidx.navigation.NavController.navigate(NavController.java:797)
at androidx.navigation.NavController.navigate(NavController.java:782)
at androidx.navigation.NavController.navigate(NavController.java:719)
at androidx.navigation.NavController.navigate(NavController.java:705)
at androidx.navigation.NavController.navigate(NavController.java:837)
我猜想在注入arguments
时sharedViewModel
为空,但是我不确定。
从trackId
获取key
时如何将parameter
用作arguments
(或者也许作为arguments
?)?
EDIT1 :我尝试使用直接的private val trackVM: TrackDetailViewModel by sharedViewModel(key = arguments?.getLong("trackId").toString())
调用,并且有效
navArgs()
所以我想EDIT1
调用有问题。
EDIT2 :根据Commonware的建议,null
并没有真正起作用,只是将key
{{1}}传递给方法。我不希望有一种使用这种方法的方法。