问题
I try create a new class that inherits from AndroidViewModel, like this
public class LoginViewModel extends AndroidViewModel {
public LoginViewModel() {}
...
But I get this message in the ide:
There is no default constructor available in 'android.arch.lifecycle.AndroidViewModel'
My happen this?
My graddle looks like this:
...
implementation 'android.arch.lifecycle:extensions:1.1.1'
...
Any idea?
Thanks
回答1:
You will need to add super call to AndroidViewModel class when inheriting from it. AndroidViewModel
class contains default constructor having Application
class as variable, so you should change your implementation as below :
public class LoginViewModel extends AndroidViewModel {
public LoginViewModel(Application application) {
super(application);
// Do rest of your stuff here ...
}
...
Default implementation of AndroidViewModel
class states that :
Application
context awareViewModel
.Subclasses must have a constructor which accepts
Application
as the only parameter.
回答2:
AndroidViewModel
has only one public constructor that takes an Application
as parameter. You must call this from your constructor:
public LoginViewModel(Application app) {
super(app);
}
回答3:
https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel
Subclasses must have a constructor which accepts Application as the only parameter.
来源:https://stackoverflow.com/questions/54462295/the-class-cannot-inherit-from-the-androidviewmodel-why