用databinding取代EditTextChangeListener 实现监听效果。
需求:只有当必填项全都填上的时候,蓝色button才会显示为可点击状态。
旧的解决方案
代码大致如下:
private void initRoomNameEditListener() {
binding.edtRoomTypeName.addTextChangedListener(new AddRoomTypeActivity.EditTextChangeListener(binding.edtRoomTypeName));
binding.edtRoomSize.addTextChangedListener(new AddRoomTypeActivity.EditTextChangeListener(binding.edtRoomSize));
}
public class EditTextChangeListener implements TextWatcher {
private EditText edtText;
public EditTextChangeListener(EditText editText) {
this.edtText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable content) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(binding.edtRoomTypeName.getText()) || TextUtils.isEmpty(binding.edtRoomSize.getText())) {
mViewModel.isCanClick.set(false);
} else {
mViewModel.isCanClick.set(true);
}
}
}
在mViewModel 中设置变量,enbable用zhe'g
新解决方案:
因为Databinding自带可以观察的字段,我们巧妙利用:
为每一项添加这样的字段:
public ObservableField<String> chamberName = new ObservableField<>();
public ObservableField<String> rent = new ObservableField<>();
并在viewmodel中同时增加如下方法,这样利用原生的Observable,我们就自然实现了监听。不用采用
public boolean getIsCanCreate(){
return (!TextUtils.isEmpty(rent.get()))&&(!TextUtils.isEmpty(chamberName.get()));
}
以上代码应该不正确,但是感觉似乎也是一种思路。不知道到有实现的没有: