如何一起使用Koin sharedViewModel()和NavigationComponent navArgs()

时间:2019-01-31 12:10:23

标签: android android-fragments kotlin android-architecture-navigation koin

我正在尝试使用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)

我猜想在注入argumentssharedViewModel为空,但是我不确定。

trackId获取key时如何将parameter用作arguments(或者也许作为arguments?)?

EDIT1 :我尝试使用直接的private val trackVM: TrackDetailViewModel by sharedViewModel(key = arguments?.getLong("trackId").toString()) 调用,并且有效

navArgs()

所以我想EDIT1调用有问题。

EDIT2 :根据Commonware的建议,null并没有真正起作用,只是将key {{1}}传递给方法。我不希望有一种使用这种方法的方法。

0 个答案:

没有答案