带有导航控制器的Android Nested ViewModel



我有一项活动,内部有片段( parent fragment (。

parent fragment 具有带有多个片段的导航控制器的片段。

parentfragment的 ViewModel具有标题,字幕和颜色属性。

每次我导航到另一个片段时,都应更新 parentfragment的 viewModel数据(这些片段是带有数据的片段(,我该如何实现?

我知道如何共享一个ViewModel,它不符合项目的需求,每个片段都应具有其ViewModel,并且对于 parent fordfragment

相同
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.
    }
}

您需要在 childviewModel

中实现 ParentViewModel
class ChildViewModel : ParentViewModel() {
    init {
        title = "Title"
        subtitle = "Sub Title"
        color = -123454
        // I need to access ParentViewModel and update title, subtitle and color here.
    }
}

最新更新