Last active
October 10, 2017 18:04
-
-
Save joaopedronardari/0c111decf2f6eb13f7519e67f833b1cb to your computer and use it in GitHub Desktop.
Brazilian Phone Number Formatter
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.text.Editable; | |
import android.text.TextWatcher; | |
import android.widget.EditText; | |
public class PhoneMask implements TextWatcher { | |
private static final String PHONE_MASK = "(##)####-####"; | |
private final char[] PHONE_MASK_ARRAY = PHONE_MASK.toCharArray(); | |
private boolean isInTextChanged; | |
private boolean isInAfterTextChanged; | |
private EditText editText; | |
private int shiftCursor; | |
private String text; | |
private int cursor; | |
public PhoneMask(EditText editText) { | |
super(); | |
this.editText = editText; | |
isInTextChanged = false; | |
isInAfterTextChanged = false; | |
} | |
@Override | |
public synchronized void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
shiftCursor = after - count; | |
} | |
@Override | |
public synchronized void onTextChanged(CharSequence s, int start, int before, int count) { | |
if (!isInTextChanged) { | |
isInTextChanged = true; | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < s.length(); i++) { | |
char symbol = s.charAt(i); | |
if (symbol >= '0' && symbol <= '9') | |
sb.append(symbol); | |
} | |
String digits = sb.toString(); | |
sb.setLength(0); | |
int j = 0; | |
for (int i = 0; i < digits.length(); i++) { | |
char digit = digits.charAt(i); | |
while (j < PHONE_MASK_ARRAY.length) { | |
if (PHONE_MASK_ARRAY[j] == '#') { | |
sb.append(digit); | |
j++; | |
break; | |
} else { | |
sb.append(PHONE_MASK_ARRAY[j]); | |
j++; | |
} | |
} | |
} | |
cursor = editText.getSelectionStart(); | |
text = sb.toString(); | |
if (shiftCursor > 0) { | |
if (cursor > text.length()) | |
cursor = text.length(); | |
else { | |
while (cursor < PHONE_MASK_ARRAY.length && PHONE_MASK_ARRAY[cursor - 1] != '#') { | |
cursor++; | |
} | |
} | |
} else if (shiftCursor < 0) { | |
while (cursor > 0 && PHONE_MASK_ARRAY[cursor - 1] != '#') { | |
cursor--; | |
} | |
} | |
} | |
} | |
public synchronized void afterTextChanged(Editable s) { | |
if (!isInAfterTextChanged) { | |
isInAfterTextChanged = true; | |
editText.setText(text); | |
editText.setSelection(cursor); | |
isInTextChanged = false; | |
isInAfterTextChanged = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on this stackoverflow: http://stackoverflow.com/questions/5645332/android-edittext-keyboard-textwatcher-problem