Skip to content

Instantly share code, notes, and snippets.

@hitesh-dhamshaniya
Created November 25, 2021 13:36
Show Gist options
  • Save hitesh-dhamshaniya/01886548d082bcde4b7132864d28cf0a to your computer and use it in GitHub Desktop.
Save hitesh-dhamshaniya/01886548d082bcde4b7132864d28cf0a to your computer and use it in GitHub Desktop.
CPF Formatter for Edit text add as a TextWatcher in Edit text for text change listener.
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class CPFFormatter implements TextWatcher {
private final String CPF_MASK = "###.###.###-##";
private final char[] CPF_MASK_ARRAY = CPF_MASK.toCharArray();
private boolean isInTextChanged = false;
private boolean isInAfterTextChanged = false;
private EditText editText;
private String text;
private int shiftCursor;
private int cursor;
public CPFFormatter(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 (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 < CPF_MASK_ARRAY.length) {
if (CPF_MASK_ARRAY[j] == '#') {
sb.append(digit);
j++;
break;
} else {
sb.append(CPF_MASK_ARRAY[j]);
j++;
}
}
}
cursor = editText.getSelectionStart();
text = sb.toString();
if (shiftCursor > 0) {
if (cursor > text.length())
cursor = text.length();
else {
while (cursor < CPF_MASK_ARRAY.length && CPF_MASK_ARRAY[cursor - 1] != '#') {
cursor++;
}
}
} else if (shiftCursor < 0) {
while (cursor > 0 && CPF_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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment