在不同的片段上使用相同的视图模型

Using same viewmodel on different fragments

我在 Fragment A 上有 viewModel,我是这样加载的:

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

然后从片段 A 转到片段 B。是否可以在片段 B 上使用相同的视图模型?在 Fragment B 中,我尝试过(如文档中所示):

private val viewModel: AFragmentVM by activityViewModels()

但我在尝试使用此 ViewModel 时遇到异常:

java.lang.RuntimeException: Cannot create an instance of class ...AFragmentVM
...
BFragment.getViewModel(Unknown Source:2)
BFragment.onCreateView(ChartFragment.kt:40)
...
Caused by: java.lang.NoSuchMethodException: ...AFragmentVM.<init> [class android.app.Application]

编辑:

根据@SebastienRieu 和@IntelliJ Amiya 的回答,我所要做的就是以这种方式在 Fragment A 上创建 ViewModel:

viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)

或者:

viewModel  = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)

然后在 Fragment B 上我可以使用:

private val viewModel: AFragmentVM by activityViewModels()

如果这两个片段在同一个 activity 你应该替换这个:

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

由此

viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)

并在 activity 中添加一个 viewModel 并在此 activity 中初始化它,如下所示:

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

使用 requireActivity() 在片段中设置 VM 时,您告诉片段使用 activity 共享 ViewModel

片段A

viewModel  = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)

片段 B

 private lateinit var viewModel: AFragmentVM