Skip to content

Instantly share code, notes, and snippets.

@leonardo2204
Created February 3, 2016 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardo2204/5d5eb3f91136e5a2bd1a to your computer and use it in GitHub Desktop.
Save leonardo2204/5d5eb3f91136e5a2bd1a to your computer and use it in GitHub Desktop.
TextInputLayoutClearable. When an error is shown, if user starts typing, the error is automatically cleared.
package com.lukaspili.mortardemo.ui.custom;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
/**
* Created by Leonardo on 03/02/2016.
*/
public class TextInputLayoutClearable extends TextInputLayout {
boolean isTextWatcherSetup;
TextWatcher textWatcher = 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) {
setError(null);
}
};
public TextInputLayoutClearable(Context context) {
super(context);
}
public TextInputLayoutClearable(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextInputLayoutClearable(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setError(@Nullable CharSequence error) {
super.setError(error);
if (!this.isTextWatcherSetup && isErrorEnabled())
setupTextWatcher();
else if (this.isTextWatcherSetup && error == null)
removeTextWatcher();
}
private void removeTextWatcher() {
if (this.getEditText() != null) {
this.getEditText().removeTextChangedListener(textWatcher);
this.isTextWatcherSetup = false;
}
}
private void setupTextWatcher() {
if (this.getEditText() != null) {
this.getEditText().addTextChangedListener(textWatcher);
this.isTextWatcherSetup = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment