问题描述
我正在尝试使用viewModels
从ChildFragment
访问ParentFragment
的ParentViewModel
.这是我的代码.
I am trying to access the ParentViewModel
for ParentFragment
from ChildFragment
using viewModels
. This is my code.
// In ParentFragment
class ParentFragment : Fragment() {
val parentViewModel: ParentViewModel by viewModels {
ParentViewModelFactory(getRepository())
}
...
}
// In ChildFragment
class ChildFragment : Fragment() {
val parentViewModel: ParentViewModel by viewModels(
{ requireParentFragment() }
)
...
}
但是,仅当我在ParentViewModel
中设置LiveData
变量并使ParentFragment
如此观察时,此代码才有效:
However, this code only works when I setup a LiveData
variable in ParentViewModel
and have ParentFragment
observe it like so:
parentViewModel.text.observe(this) {
toast(it)
}
我没有必要从ParentFragment
内部观察ViewModel
.我只需要它为ChildFragments
定义lifecycle
.
I have no use for observing the ViewModel
from inside ParentFragment
. I only need it to define the lifecycle
for the ChildFragments
.
如果我摆脱上面的观察,就会收到此错误:
If I get rid of the observation above I get this error:
如何让ChildFragments访问ParentViewModel
而不设置虚拟活动数据对象,以便ParentFragment
可以观察它们.
How can I have the ChildFragments access the ParentViewModel
without setting up dummy live data objects so as the ParentFragment
can observe them.
推荐答案
在ChildFragment中,您应该在初始化时传递工厂.试试这个
In ChildFragment you should pass factory when init it. Try this
class ChildFragment : Fragment() {
val parentViewModel: ParentViewModel by viewModels(
{ requireParentFragment() }
) { ParentViewModelFactory(getRepository()) }
...
}
这篇关于使用viewModels从ChildFragment访问ParentFragment中的ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!