Open anderscheow opened 7 years ago
Create TextInputLayoutAdapter
public class TextInputLayoutAdapter implements ViewDataAdapter<TextInputLayout, String> {
@Override
public String getData(final TextInputLayout til) {
return getText(til);
}
private String getText(TextInputLayout til) {
return til.getEditText().getText().toString();
}
}
Define your validation
@NotEmpty
@BindView(R.id.til_username)
TextInputLayout mTilUsername;
implement Validator.ValidationListener and define Validator var
public class YourActivityOrFragment extends AppCompatActivity implements Validator.ValidationListener {
private Validator mValidator; ...
private void initValidator() {
mValidator=new Validator(this);
mValidator.setValidationListener(this);
mValidator.registerAdapter(TextInputLayout.class, new TextInputLayoutAdapter());
mValidator.setViewValidatedAction(view -> {
if (view instanceof TextInputLayout) {
((TextInputLayout) view).setError("");
((TextInputLayout) view).setErrorEnabled(false);
}
});
}
@Override
public void onValidationSucceeded() {
}
@Override
public void onValidationFailed(List<ValidationError> errors) {
errors.get(0).getView().requestFocus();
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(this);
if (view instanceof TextInputLayout) {
((TextInputLayout) view).setError(message);
((TextInputLayout) view).setErrorEnabled(true);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}
...
PS Don't forget to call initValidator().
Worked for me. Thanks
error: lambda expressions are not supported in -source 1.7
(use -source 8 or higher to enable lambda expressions)
How do set the error message from TextInputEditText to TextInputLayout???