gpt4 book ai didi

Android 架构组件 ViewModel 上下文

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:21 27 4
gpt4 key购买 nike

我正在研究谷歌的架构组件来为我的应用程序实现 ViewModel 和 LiveData,官方文档说:

Note: Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. If the ViewModel needs the Application context (for example, to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor (since Application class extends Context)

之后,我得到了这样的代码:

public class ViewModelTest extends AndroidViewModel {

public ViewModelTest(Application application) {
super(application);
}

public void test(){
Prefs.getCurrentCode(getApplication());
}

我应该在 Activity 中正常实例化它吗?

  val viewModel2 = ViewModelProviders.of(this).get(ViewModelTest::class.java)
viewModel2.test()

这不是很糟糕吗?要在需要访问 SharedPreferences 或任何需要上下文的内容时使用此应用程序变量?如果是,我是否应该避免在 ViewModel 上使用它而只在 View 上使用它?特别是如果我想用需要上下文的值更新 UI 组件。我有点不知道如何解决这个问题,我愿意接受任何建议。

提前致谢

最佳答案

AndroidViewModel 类是作为 android.arch.lifecycle 包的一部分提供的,它是 Android 架构组件的一部分。它本身调用传递给构造函数的应用程序上下文。 Application Context 存在于 Activity 生命周期中。

ViewModel 中的 Application 上下文是可以的,因为 Application 上下文与整个 Application 生命周期相关联,而不是 Activity 上下文,后者与 Activity 生命周期相关联。

ViewModel 文档特别提到不使用 Activity Context,但可以使用 Application Context。

关于Android 架构组件 ViewModel 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46300395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com