我正在体验数据绑定。我知道通过扩展BaseObservable
我的 POJO(用户),我可以更新布局中的链接元素,例如使用,android:text="@={user.name}"
但我有兴趣在属性更改时做不同的工作人员。例如,应用一些逻辑,或显示 toast 消息。我期望类似于该liveDataObject.observe()
方法,但是当属性更改时它没有反应。这是我的代码:
视图模型:
public class MainViewModel extends ViewModel {
private MutableLiveData<User> user; //getter and setter
模型:
public class User extends BaseObservable {
private String name;
public User() {}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
分段:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
mDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.main_fragment, container, false);
mDataBinding.setLifecycleOwner(this);
return mDataBinding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);
mViewModel.getUser().observe(getViewLifecycleOwner(), user ->
Toast.makeText(getActivity().getApplicationContext(), user.getName(), Toast.LENGTH_SHORT).show()
);
}