Accessing ViewModel in ParentFragment from ChildFragment using viewModels

时光怂恿深爱的人放手 提交于 2021-01-29 20:30:27

问题


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() }
    )
    ...
}

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)
}

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: Cannot create an instance of class ParentViewModel'
How can I have the ChildFragments access the ParentViewModel without setting up dummy live data objects so as the ParentFragment can observe them.

回答1:


In ChildFragment you should pass factory when init it. Try this

class ChildFragment : Fragment() {
    val parentViewModel: ParentViewModel by viewModels(
        { requireParentFragment() }
    ) { ParentViewModelFactory(getRepository()) }
    ...
}


来源:https://stackoverflow.com/questions/62040836/accessing-viewmodel-in-parentfragment-from-childfragment-using-viewmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!