本文介绍了将应用程序传递给AndroidViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的视图中使用 AndroidViewModel 模型以访问Context
.它要求Application
作为参数传递.我的ViewModel类如下:
I would like to use AndroidViewModel for my view model in order to get access to the Context
. It requires Application
to be passed as a parameter. My ViewModel class looks like this:
class FooAndroidViewModel(application: Application?) : AndroidViewModel(aplication) {
...
}
它正像这样被实例化:
val fooModel = ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)
问题在于这会产生错误,无法实例化FooAndroidViewModel
-可能是由于缺少application
参数所致.
The problem is that this gives an error, that FooAndroidViewModel
cannot be instantiated - probably because of the missing application
parameter.
问题:如何将application
传递给ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)
?
推荐答案
只需将application: Application?
替换为application: Application
.
以下代码应该可以工作:
Following code should work:
class FooAndroidViewModel(application: Application) : AndroidViewModel(aplication) {
...
}
这篇关于将应用程序传递给AndroidViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!