如何实例化扩展AndroidViewModel的ViewModel? [英] How to instantiate ViewModel that extends AndroidViewModel?

查看:68
本文介绍了如何实例化扩展AndroidViewModel的ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一个教程,其中ViewModel扩展了一个抽象类以使用协程,这是扩展的类:

I'm following a tutorial where a ViewModel extends an abstract class in order to use coroutines, this is the class that extends:

abstract class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope {
private val job =  Job()

override val coroutineContext: CoroutineContext
    get() = job + Dispatchers.Main

override fun onCleared() {
    super.onCleared()
    job.cancel()
}}

这是ViewModel:

And this is the ViewModel:

class ViewModel(application: Application) : BaseViewModel(application) {}

所以在MainActivity中,我试图像这样实例化该类:

So in MainActivity I'm trying to instantiate the class like this:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this)[ViewModel::class.java]}

在教程中,这个家伙完美地做到了这一点,但是当我尝试运行该应用程序时,它抛出了一个异常:

In the tutorial the guy perfectly does this but when I try to run the application it throws me an exception:

 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.name.nameapp.main.viewmodel.ViewModel

我觉得我想念一些东西,你们可以指出它是什么,如果您需要更多信息,我会很乐意将其张贴

I feel like I'm missing something can you guys point what it is, if you need more information I'll gladly post it

推荐答案

您的 ViewModel AndroidViewModel 的子级,需要一个 Application 对象.因此,您必须提供 Factory 类才能实例化 ViewModel .像这样:

Your ViewModel is child of AndroidViewModel which require an Application object. So you will have to provide the Factory class in order to instantiate the ViewModel. Like so:

val viewModelProvider = ViewModelProvider(
     this, 
     ViewModelProvider.AndroidViewModelFactory(application)
)
viewModel = viewModelProvider[MainViewModel::class.java]

如果您正在使用Jetpack的片段库

If you are using the fragment library from Jetpack

implementation "androidx.fragment:fragment-ktx:1.2.5"

您可以像这样使用属性委派:

You can use property delegation like so:

val viewModel: ViewModel by viewModels()

这篇关于如何实例化扩展AndroidViewModel的ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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