按照android给出的示例,我扩展了ViewModel类
public class NameViewModel extends ViewModel {
private MutableLiveData<String> currentName;
public MutableLiveData<String> getCurrentName() {
if (currentName == null) {
currentName = new MutableLiveData<String>();
}
return currentName;
}}
我观察了LiveData对象
public class NameActivity extends AppCompatActivity {
private NameViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other code to setup the activity...
// Get the ViewModel.
model = new ViewModelProvider(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
nameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.getCurrentName().observe(this, nameObserver);
}}
我在build.gradle中的依赖项是
dependencies {
def lifecycle_version = "2.2.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
运行此代码将导致无法创建类NameViewModel的实例,我在这里做什么错了?
答案 0 :(得分:1)
您在ViewModel类中缺少构造函数,因此将public NameViewModel() {};
添加到ViewModel中。
答案 1 :(得分:0)
代码似乎没什么问题。
您能否检查build.gradle中是否具有此特定的依赖版本
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
,您能添加您的build.gradle吗?
答案 2 :(得分:0)
也许您应该在ViewModel
调用super()
中添加一个空的构造函数吗?
答案 3 :(得分:0)
我将NameViewModel与NameActivity放在同一个Java文件中,该文件应放在单独的文件NameViewModel.java中,对此进行了修复。
答案 4 :(得分:0)
相反:
model = new ViewModelProvider(this).get(NameViewModel.class);
试试这个:
model = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NameViewModel.class);