Skip to content

Instantly share code, notes, and snippets.

@MatheusAmelco
Forked from joaopedronardari/PhoneMask.java
Last active October 18, 2017 13:28
Show Gist options
  • Save MatheusAmelco/b68279b8ab25d96a4e98dfd911470992 to your computer and use it in GitHub Desktop.
Save MatheusAmelco/b68279b8ab25d96a4e98dfd911470992 to your computer and use it in GitHub Desktop.
Brazilian Phone Number Formatter for Android
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class PhoneFormatter implements TextWatcher {
private static final String PHONE_MASK = "(##) #####-####";
private final char[] PHONE_MASK_ARRAY = PHONE_MASK.toCharArray();
private boolean isInTextChanged = false;
private boolean isInAfterTextChanged = false;
private EditText editText;
private String text;
private int shiftCursor;
private int cursor;
public PhoneFormatter(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
shiftCursor = after - count;
}
@Override
public 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 (i == 0 && symbol == '0') {
return;
}
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--;
}
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (!isInAfterTextChanged) {
isInAfterTextChanged = true;
editText.setText(text);
editText.setSelection(cursor);
isInTextChanged = false;
isInAfterTextChanged = false;
}
}
@MatheusAmelco
Copy link
Author

Code suitable for the new format of Brazilian phone numbers and it's no longer possible to enter the number 0 at the beginning, because there are no DDDs that start with 0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment