Skip to content

Instantly share code, notes, and snippets.

@rafaelneiva
Created April 23, 2019 20:41
Show Gist options
  • Save rafaelneiva/2c64a5e6a1ad570beb8aaf9d407cab32 to your computer and use it in GitHub Desktop.
Save rafaelneiva/2c64a5e6a1ad570beb8aaf9d407cab32 to your computer and use it in GitHub Desktop.
Android Mask for EditText that allows erasing pressing and holding backspace
public abstract class MaskUtils {
public static TextWatcher mask(final EditText editText, final String mask) {
return new TextWatcher() {
int mBefore;
int mCount;
public void onTextChanged(CharSequence s, int start, int before, int count) {
mBefore = before;
mCount = count;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
String value = unmask(s.toString());
String maskAux = "";
int i = 0;
for (char m : mask.toCharArray()) {
if (m != '#') {
maskAux += m;
continue;
}
try {
maskAux += value.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
if (!unmask(maskAux).equals(value) || mCount > mBefore) {
editText.setText(maskAux);
editText.setSelection(maskAux.length());
}
editText.addTextChangedListener(this);
}
};
}
public static String unmask(String s) {
return s.replaceAll("[.]", "").replaceAll("[-]", "")
.replaceAll("[/]", "").replaceAll("[(]", "")
.replaceAll("[)]", "").replaceAll(" ", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment