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

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

问题描述

我目前正在研究Android Room with a View示例应用程序,完整的源代码可用AndroidViewModel的WordViewModel.kt"rel =" nofollow noreferrer> WordViewModel :

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实例. 但是,当我检查

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,该方法通过您的活动/片段"返回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通常是更好的主意,以便能够以类似的方式(___(application, savedStateHandle))接收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天全站免登陆