使用viewModels从ChildFragment访问ParentFragment中的ViewModel [英] Accessing ViewModel in ParentFragment from ChildFragment using viewModels

查看:156
本文介绍了使用viewModels从ChildFragment访问ParentFragment中的ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用viewModelsChildFragment访问ParentFragmentParentViewModel.这是我的代码.

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:

'java.lang.RuntimeException:无法创建类ParentViewModel的实例'
'java.lang.RuntimeException: Cannot create an instance of class ParentViewModel'

如何让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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆