安卓Android LiveData 超简单实例
前言
提示:这里可以添加本文要记录的大概内容:
便于理解
提示:以下是本篇文章正文内容,下面案例可供参考
使用步骤
1.实例化
代码如下(示例):
public class HomeViewModel extends ViewModel {
public final MutableLiveData<UserEntity> mUserEntityMutableLiveData = new MutableLiveData<>();
}
2.搞个实体类
代码如下(示例):
public class UserEntity extends BaseObservable {
public String username;
public String password;
public int userId;
public String code;
public UserEntity(String username, String password, int userId, String code) {
this.username = username;
this.password = password;
this.userId = userId;
this.code = code;
}
@Bindable
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
notifyPropertyChanged(BR.username);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "UserEntity{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", userId=" + userId +
", code='" + code + '\'' +
'}';
}
}
3.将消息发送给观察者
代码如下(示例):
mUserEntityMutableLiveData.postValue(new UserEntity("wangwu","12345",9,"200"));
}
4.将消息发送给观察者
代码如下(示例):
mUserEntityMutableLiveData.postValue(new UserEntity("wangwu","12345",9,"200"));
}
5.某观察者onChanged
代码如下(示例):
//观察者
private HomeViewModel mHomeViewModel;
HomeViewModel homeViewModel1 = new ViewModelProvider(this).get(HomeViewModel.class);
mHomeViewModel.mUserEntityMutableLiveData.observe(this, new Observer<UserEntity>() {
@Override
public void onChanged(UserEntity userEntity) {
String string = userEntity.toString();
Log.e("TAG", "onChanged: "+string);
}
});
}
总结
提示:这里对文章进行总结:
就是这样
本文是关于安卓Android LiveData的超简单实例,详细介绍了从实例化、创建实体类到消息发送给观察者的步骤,并提供了相关代码示例,帮助开发者快速理解和应用LiveData。

1万+

被折叠的 条评论
为什么被折叠?



