Skip to content

Instantly share code, notes, and snippets.

@danprado
Last active August 25, 2021 00:05
Show Gist options
  • Save danprado/bbfb1b59f9c53fa09dc2 to your computer and use it in GitHub Desktop.
Save danprado/bbfb1b59f9c53fa09dc2 to your computer and use it in GitHub Desktop.
Mask utility
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.TextView;
public abstract class MaskBuilder {
public static final String CREDIT_CARD_MASK = "####.####.####.####";
public static final String DATE_MASK = "##/##/####";
public static final String CPF_MASK = "###.###.###-##";
public static final String CNPJ_MASK = "##.###.###/####-##";
public static final String ZIP_CODE_MASK = "#####-###";
private MaskBuilder() {
throw new UnsupportedOperationException();
}
public static TextWatcher build(final String mask, final TextView textView) {
return new TextWatcher() {
boolean isUpdating;
String old = "";
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
isUpdating = (after == 0);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.removeTextChangedListener(this);
int selectionOffset = s.length() - count - start;
String result;
if (!isUpdating) {
result = mask(s.toString());
} else {
result = s.toString();
}
textView.setText(result);
if (selectionOffset >= 0) {
setSelection(textView, result.length() - selectionOffset);
} else {
setSelection(textView, result.length());
}
textView.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
}
private String mask(CharSequence s) {
String str = s.toString().replaceAll("[^\\d]", "");
String maskedText = "";
int i = 0;
for (char m : mask.toCharArray()) {
if (m != '#' && str.length() > old.length()) {
maskedText += m;
continue;
}
try {
maskedText += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
return maskedText;
}
};
}
private static void setSelection(TextView textView, int index) {
Selection.setSelection((Editable) textView.getText(), index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment