带有导航控制器的Android嵌套ViewModel

时间:2019-08-02 12:50:50

标签: android mvvm nested navigation viewmodel

我有一个活动,里面有一个片段( ParentFragment )。

ParentFragment 有一个片段,其导航控制器包含多个片段。

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

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

我知道如何共享一个viewModel,它不适合项目需求,每个片段都应该有其viewModel, 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.
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在 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.
    }
}
相关问题