Created
February 3, 2016 17:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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