Created
September 19, 2017 12:45
-
-
Save sergii-frost/1f83882391e5e5b3e0825e009fcb8978 to your computer and use it in GitHub Desktop.
Validatable Edit Text
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
import android.content.Context; | |
import android.support.annotation.Nullable; | |
import android.text.Editable; | |
import android.text.TextWatcher; | |
import android.util.AttributeSet; | |
import android.util.Log; | |
import java.util.regex.Pattern; | |
import java.util.regex.PatternSyntaxException; | |
public class ValidatableEditText extends android.support.v7.widget.AppCompatEditText { | |
public static final String TAG = ValidatableEditText.class.getSimpleName(); | |
public interface OnValidateListener { | |
void onValidated(boolean isValid, String input); | |
} | |
private static final String REGEX_NON_EMPTY = ".*\\S.*"; | |
private @Nullable OnValidateListener onValidateListener; | |
private boolean isValid; | |
private Pattern validationPattern; | |
public ValidatableEditText(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
init(); | |
} | |
public ValidatableEditText(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(); | |
} | |
private void init() { | |
setValidationRegex(REGEX_NON_EMPTY); | |
addTextChangedListener(new TextWatcher() { | |
@Override | |
public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
//ignore | |
} | |
@Override | |
public void onTextChanged(CharSequence s, int start, int before, int count) { | |
//ignore | |
} | |
@Override | |
public void afterTextChanged(Editable s) { | |
revalidate(validationPattern.matcher(s).matches()); | |
} | |
}); | |
} | |
private void revalidate(boolean isValid) { | |
if (this.isValid != isValid) { | |
this.isValid = isValid; | |
if (onValidateListener != null) { | |
onValidateListener.onValidated(isValid, getText().toString()); | |
} | |
} | |
} | |
public void setOnValidateListener(OnValidateListener onValidateListener) { | |
this.onValidateListener = onValidateListener; | |
} | |
public void setValidationRegex(String validationRegex) { | |
try { | |
validationPattern = Pattern.compile(validationRegex); | |
revalidate(validationPattern.matcher(getText()).matches()); | |
} catch (PatternSyntaxException e) { | |
Log.e(TAG, e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: