android - 该类不能继承自AndroidViewModel,为什么?

标签 android android-mvvm

我尝试创建一个继承自 AndroidViewModel 的新类,如下所示

public class LoginViewModel extends AndroidViewModel {

       public LoginViewModel() {}
...

但我在 ide 中收到此消息:

“android.arch.lifecycle.AndroidViewModel”中没有可用的默认构造函数

我的怎么办?

我的 graddle 看起来像这样:

...
    implementation 'android.arch.lifecycle:extensions:1.1.1'
...

有什么想法吗?

谢谢

最佳答案

您需要添加 super 调用 AndroidViewModel class 从它继承时。 AndroidViewModel 类包含 default constructorApplication 类作为变量,因此您应该按如下方式更改您的实现:

public class LoginViewModel extends AndroidViewModel {

   public LoginViewModel(Application application) {
       super(application);
       // Do rest of your stuff here ...
   }
...

AndroidViewModel 类的默认实现说明:

Application context aware ViewModel.

Subclasses must have a constructor which accepts Application as the only parameter.

关于android - 该类不能继承自AndroidViewModel,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54462295/

相关文章:

java - 如何将代码/描述扩展到复杂的对象?

java - NetworkBoundResource 类中 MediatorLiveData 的使用

Android Studio、Git及三种方式 merge

android - 是否可以将 String 参数从 Android xml 传递给 viewModel

android - 如何停止加速度计传感器

android - 应该使用什么代替 "setListNavigationCallbacks"?

android - 如何使用数据绑定(bind)在 TextView 中连接两个整数?

Android LiveData 在导航返回后观察到陈旧数据

java - ArrayList<SensorEvent>.add(...) 开始覆盖值

android - 无法安装 Android 应用程序 - INSTALL_FAILED_MISSING_SHARED_LIBRARY