Skip to content

Instantly share code, notes, and snippets.

@malvre
Last active May 29, 2018 12:18
Show Gist options
  • Save malvre/698736db403ff3ed7220 to your computer and use it in GitHub Desktop.
Save malvre/698736db403ff3ed7220 to your computer and use it in GitHub Desktop.
[Android] Mask format for EditText
Usage:
txtValor.addTextChangedListener(Mask.insert("###.###.###-##", txtValor));
public abstract class Mask {
public static String unmask(String s) {
return s.replaceAll("[.]", "")
.replaceAll("[-]", "")
.replaceAll("[/]", "")
.replaceAll("[(]", "")
.replaceAll("[)]", "");
}
public static TextWatcher insert(final String mask, final EditText ediTxt) {
return new TextWatcher() {
boolean isUpdating;
String old = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = Mask.unmask(s.toString());
String mascara = "";
if (isUpdating) {
old = str;
isUpdating = false;
return;
}
int i = 0;
for (char m : mask.toCharArray()) {
if (m != '#' && str.length() > old.length()) {
mascara += m;
continue;
}
try {
mascara += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
ediTxt.setText(mascara);
ediTxt.setSelection(mascara.length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment