-
-
Save flashfoxter/3df78a4992d4967614fd7e0e012269cc to your computer and use it in GitHub Desktop.
[Android] Mask format for EditText
This file contains hidden or 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
Usage: | |
txtValor.addTextChangedListener(Mask.insert("###.###.###-##", txtValor)); |
This file contains hidden or 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
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