Skip to content

Instantly share code, notes, and snippets.

@vishvendra01
Last active March 27, 2019 07:15
Show Gist options
  • Save vishvendra01/20e05aad018d8a9dbcdd8f2e6fe083f0 to your computer and use it in GitHub Desktop.
Save vishvendra01/20e05aad018d8a9dbcdd8f2e6fe083f0 to your computer and use it in GitHub Desktop.
Input filter for edit text which filters both letter or digits or one of these.
//todo handle cases when it erases whole text on newer android versions
public class CustomFilter implements InputFilter {
private boolean allowCharacter;
private boolean allowDigits;
public CustomFilter(boolean allowCharacter, boolean allowDigits) {
this.allowCharacter = allowCharacter;
this.allowDigits = allowDigits;
}
public void setAllowCharacter(boolean allowCharacter) {
this.allowCharacter = allowCharacter;
}
public void setAllowDigits(boolean allowDigits) {
this.allowDigits = allowDigits;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean valid = true;
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (allowCharacter && allowDigits) {
if (!(Character.isLetter(c) || Character.isDigit(c))) {
valid = false;
break;
}
} else if (allowCharacter && !Character.isLetter(c)) {
valid = false;
break;
} else if (allowDigits && !Character.isDigit(c)) {
valid = false;
break;
}
}
if (!valid) {
return "";
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment