解决方法:
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
}
public class MyViewModel extends ViewModel {
private MutableLiveData data = new MutableLiveData<>();
public LiveData getData() {
return data;
}
public void updateData(String newData) {
data.setValue(newData);
}
}
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this);
viewModel.getData().observe(this, new Observer() {
@Override
public void onChanged(String newData) {
// 处理数据变化事件
}
});
}
}
这样,当点击按钮时,ViewModel中的数据会更新,并且布局文件中的TextView会自动更新显示新的数据。在Activity或Fragment的生命周期事件中可以处理数据的变化。