If you want to do something like EditText.setError() function with databinding, here is two method.
Method 1
Used the final EditText view generated from the data binding (
https://developer.android.com/topic/libraries/data-binding/index.html#views_with_ids)
You can call the EditText directly without creating it manually since it is automatically generated after you set the id for the view (also true for the included layout) .
MainActivityBinding.etext_uname.setError("Wrong email format");
Or
MainActivityBinding.etext_uname.addTextChangedListener(new MyOwnTextWatcher());
Method 2
If you want to use the binding method with xml as George mentioned (
https://medium.com/google-developers/android-data-binding-custom-setters-55a25a7aea47#.su88ujqrn)
First you have to set your own binding method. Suggest to create another class for all the binding method.
Method must be static, with @BindingAdapter annotation and the corresponding binding method name (Namespace and the method name can be customized)
1. Set the Custom TextWatcher
public class MyOwnBindingUtil {
public interface StringRule {
public boolean validate(Editable s);
}
@BindingAdapter("android:watcher")
public static void bindTextWatcher(EditText pEditText, TextWatcher pTextWatcher) {
pEditText.addTextChangedListener(pTextWatcher);
}
@BindingAdapter(value = {"email:rule", "email:errorMsg"}, requireAll = true)
public static void bindTextChange(final EditText pEditText, final StringRule pStringRule, final String msg) {
pEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!pStringRule.validate(s)) {
pEditText.setError(msg);
}
}
});
}
/*
Your other custom binding method
*/
}
If you want to setup your own TextWatcher with custom action, like Toast shown, Dialog shown. You should use "android:watcher" method
mBinding.setWatcher(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
In xml,
<?xml version="1.0" encoding="utf-8"?>
2. Setup your own validation Rule and error Msg
If you want to use setError function and only left the errorMsg and validation logic to be customized. You can set the xml like the following.
In xml,
<?xml version="1.0" encoding="utf-8"?>
Activity code
mBinding.setErrorMsg("Wrong type");
mBinding.setEmailRule(new MyOwnBindingUtil.StringRule() {
@Override
public boolean validate(Editable s) {
// check if the length of string is larger than 18
return s.toString().length() > 18;
}
});
Please feel free to edit my code to make the binding be more generic for the developer use.