I have an activity with a fragment inside ( ParentFragment ).
The ParentFragment has a fragment with its navigation controller with multiple fragments.
The ParentFragment's ViewModel has title, subtitle and color properties.
Every time I navigate to another fragment the ParentFragment's ViewModel data should be updated (the fragments are the ones with the data), how can I achieve that?
I know how to share a viewModel, It doesn't fit the project needs, each fragment should have its viewModel, and the same for the ParentFragment .
class ParentFragment: Fragment() {
private lateinit var parentViewModel: ParentViewModel
}
class ChildFragment: Fragment() {
private lateinit var childViewModel: ChildViewModel
}
class ParentViewModel : ViewModel() {
var title: String? = null
var subtitle: String? = null
var color: Int? = null
}
class ChildViewModel : ViewModel() {
init {
// I need to access ParentViewModel and update title, subtitle and color here.
}
}
you need to implement ParentViewModel in ChildViewModel
class ChildViewModel : ParentViewModel() {
init {
title = "Title"
subtitle = "Sub Title"
color = -123454
// I need to access ParentViewModel and update title, subtitle and color here.
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.