Issue
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.
Solution
In ChildFragment you should pass factory when init it. Try this
class ChildFragment : Fragment() {
val parentViewModel: ParentViewModel by viewModels(
{ requireParentFragment() }
) { ParentViewModelFactory(getRepository()) }
...
}
Answered By - Công Hải
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.