开始
LiveData需要配合ViewModel使用, 需要导入第三方库
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.2@aar'
ViewModel用法
创建自己的ViewModel
public class MyViewModel extends ViewModel {
private MutableLiveData<String> name;
private MutableLiveData<User> user;
public MyViewModel() {
name = new MutableLiveData<>();
user = new MutableLiveData<>();
}
public MutableLiveData<String> getName() {
return name;
}
public MutableLiveData<User> getUser() {
return user;
}
}
class User {
String account_name = "User"
}
在Application中实现ViewModelStoreOwner
public class MyApplication extends Application implements ViewModelStoreOwner {
@NonNull
@Override
public ViewModelStore getViewModelStore() {
return viewModelStore;
}
private ViewModelStore viewModelStore = new ViewModelStore();
// other code
}
发送全局数据更新
MyViewModel myViewModel = new ViewModelProvider(MyApplication.getApp()).get(MyViewModel.class);
user.account_name = new Date().toString();
myViewModel.getUser().postValue(user);
接受全局数据更新
MyViewModel myViewModel = new ViewModelProvider(MyApplication.getApp()).get(MyViewModel.class);
myViewModel.getUser().observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
// binding.tvBaseUrl2.setText(user.account_name); // 更新UI
}
});