如何使用ViewModelProvider获取扩展AndroidViewModel的自定义ViewModel?

问题描述 投票:0回答:1

我有一个自定义的ViewModel,它扩展了AndroidViewModel。在自定义ViewModel的构造函数中,我正在传递应用程序。

[在主活动中,我尝试使用ViewModel

CustomViewModel customViewModel = ViewModelProviders.to(this)...

但是它说这是不推荐使用的方法。所以我想使用ViewModelProvider,但是我看到它没有参数。

然后我如何通过申请?

android android-viewmodel android-mvvm
1个回答
0
投票
    ViewModelProviders.of(this)[CustomViewModel::class.java]

您可以使用of方法代替to。尽管您不能像这样为应用程序类创建ViewModel,但还有另一件事。 of方法仅采用Activity和Fragment类。

© www.soinside.com 2019 - 2024. All rights reserved.