如何使用Google的GithubBrowserSample方法在片段之间共享视图模型? [英] How to share view models between fragments using Google's GithubBrowserSample approach?

查看:51
本文介绍了如何使用Google的GithubBrowserSample方法在片段之间共享视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Android体系结构组件的新手,因此我决定使用GithubBrowserSample建立我的应用程序基础,以实现许多用例.但是我有一个问题,就是我不知道用这种方法在片段之间共享视图模型的正确方法是什么.

I am very new using Android architecture components, so I decided to base my application using GithubBrowserSample to achieve many of my use cases. But i have the problem that i don´t know what is the correct way to share viewmodels between fragments with this approach.

我想共享视图模型,因为我有一个带有viewpager的片段,其中有2个需要观察父片段视图模型数据的片段

I want to share the view model because i have a fragment with a viewpager with 2 fragments that need to observe data of the parent fragment view model

根据 google的文档

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    model = activity?.run {
        ViewModelProviders.of(this)[SharedViewModel::class.java]
    } ?: throw Exception("Invalid Activity")
}

但使用了生命周期扩展:2.2.0-alpha03似乎已被弃用

but with the lifecycle-extensions:2.2.0-alpha03 seems to be deprecated

在GithubBrowserSample中,它们具有类似的功能来创建视图模型的实例,但是每次看来它都是一个不同的实例

In GithubBrowserSample they have something like this to create an instance of a view model, but with this it seems to be a different instance every time

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private val userViewModel: UserViewModel by viewModels {
    viewModelFactory
}

我不知道将活动范围传递到哪里或是否应该传递它.

And i don't know where to pass the activity scope or if I should pass it.

我尝试过这样的事情

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private lateinit var myViewModel: MyViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    myViewModel = activity?.run {
        ViewModelProvider(this, viewModelFactory).get(MyViewModel::class.java)
    } ?: throw Exception("Invalid Activity")
}

但是我得到了

kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized

希望您能为我提供帮助,我对此有点迷惑,对不起,如果我的英语不太好

I hope you can help me, i'm a little lost with this, sorry if my english it´s not that good

推荐答案

by viewModels()提供了一个适用于单个Fragment的ViewModel.有一个单独的 by activityViewModels() ViewModel添加到您的活动中.

by viewModels() provides a ViewModel that is scoped to the individual Fragment. There's a separate by activityViewModels() that scopes the ViewModel to your Activity.

但是,ViewModelProviders.of(this)的直接替代品只是ViewModelProvider(this)-使用lifecycle-extensions:2.2.0-alpha03

However, the direct replacement for ViewModelProviders.of(this) is simply ViewModelProvider(this) - you aren't required to switch to by viewModels() or by activityViewModels() when using lifecycle-extensions:2.2.0-alpha03

这篇关于如何使用Google的GithubBrowserSample方法在片段之间共享视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆