AndroidViewModel 实例化而不传递应用程序上下文? [英] AndroidViewModel instantiated without passing application context?

查看:34
本文介绍了AndroidViewModel 实例化而不传递应用程序上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究 Android Room with a View 示例应用程序,完整的源代码可用 此处.在这个项目中,一个 WordViewModel 定义了 AndroidViewModel 类型:

I am currently digging through the Android Room with a View sample app, full source code available here. In this project, an WordViewModel of type AndroidViewModel is defined:

class WordViewModel(application: Application) : AndroidViewModel(application)

注意构造函数如何要求传入一个 Application 实例.然而,当我检查 MainActivity,检索WordViewModel,不传入Application 实例:

Note how the constructor requires an Application instance to be passed in. Yet when I check the MainActivity, the WordViewModel is retrieved without passing in the Application instance:

// Get a new or existing ViewModel from the ViewModelProvider.
mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class);

这怎么可能,如何在不传入 Application 实例且不使用自定义工厂的情况下检索 WordViewModel?

How is that possible, how can the WordViewModel be retrieved without passing in the Application instance and without using a custom factory?

推荐答案

AndroidX-Activity 1.2.0 的 ComponentActivity(因此 AppCompatActivity)实现了 HasDefaultViewModelProviderFactory,默认情况下从您的 Activity/Fragment 返回一个 ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()),允许您从这个 AndroidViewModelFactory 获取应用程序,而无需您显式传递它.

AndroidX-Activity 1.2.0's ComponentActivity (and therefore AppCompatActivity) implements HasDefaultViewModelProviderFactory, which returns an ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()) from your Activity/Fragment by default, allowing you to get the application from this AndroidViewModelFactory without you having to explicitly pass it.

然后,这个工厂使用 __(application) 构造函数通过反射实例化你的 ViewModel.

Then, this factory instantiates your ViewModel via reflection using a __(application) constructor.

使用 SavedStateViewModelFactory 通常是一个更好的主意,以便能够以类似的方式接收 SavedStateHandle (___(application, savedStateHandle)代码>)虽然.

It's generally a better idea to use SavedStateViewModelFactory in order to be able to receive a SavedStateHandle in a similar manner (___(application, savedStateHandle)) though.

所以要解决这个问题,你需要添加最新版本的core-ktxactivity-ktxfragment-ktx 明确在您的代码中.

So to fix the problem, you need to add up-to-date versions of core-ktx, activity-ktx and fragment-ktx explicitly in your code.

这篇关于AndroidViewModel 实例化而不传递应用程序上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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