TextWatcher is used when an object of a type is attached to an Editable, its methods will be called when the text is changed. Here is the simplest way to set up Textwatcher:
EditText inputName = (EditText) findViewById(R.id.input_name);
EditText inputEmail = (EditText) findViewById(R.id.input_email);
EditTextinputPassword = (EditText) findViewById(R.id.input_password);
TextInputLayout inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword))
Validate email
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
Check wheather email valid or not,
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Implements them,
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name:
validateName();
break;
case R.id.input_email:
validateEmail();
break;
case R.id.input_password:
validatePassword();
break;
}
}
}
I hope this will helpful for you.