ViewModel处理配置更改的具体方法是将ViewModel与生命周期组件一起使用,在Activity或Fragment被销毁并重新创建时,ViewModel能够存储和恢复数据。具体实现方式是在ViewModel类中创建和管理LiveData对象,LiveData会在配置更改后自动通知它的观察者们进行数据更新操作。
示例如下:
public class MyViewModel extends ViewModel {
private MutableLiveData data;
public LiveData getData() {
if (data == null) {
data = new MutableLiveData();
loadData();
}
return data;
}
private void loadData() {
//Load data from database or network
data.setValue("Data loaded");
}
}
在Activity或Fragment中使用ViewModel:
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.getData().observe(this, new Observer() {
@Override
public void onChanged(@Nullable String s) {
//Update UI with new data
}
});
}
}