1

我正在尝试注入一个sharedViewModelusingarguments作为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在从?keyparameterarguments

EDIT1:我尝试使用直接arguments调用并且它有效

private val trackVM: TrackDetailViewModel by sharedViewModel(key = arguments?.getLong("trackId").toString())

所以我猜这个navArgs()电话有问题。

EDIT2:正如Commonware所建议的,EDIT1它并没有真正起作用,它只是将 a 传递null key给该方法。我对有办法使用这种方法失去了希望。

4

0 回答 0