Skip to content

Instantly share code, notes, and snippets.

@diegoy
Last active November 22, 2021 08:41
Show Gist options
  • Save diegoy/7d9d993fb1f1bdd898c192a9f0bc06a9 to your computer and use it in GitHub Desktop.
Save diegoy/7d9d993fb1f1bdd898c192a9f0bc06a9 to your computer and use it in GitHub Desktop.
Apply masks to Android's Edit text adding this TextWatcher
/*
MIT License
Copyright (c) 2016 Diego Yasuhiko Kurisaki
*/
/* Example:
mEmailView.addTextChangedListener(new MaskWatcher("###-##"));
*/
import android.text.Editable;
import android.text.TextWatcher;
public class MaskWatcher implements TextWatcher {
private boolean isRunning = false;
private boolean isDeleting = false;
private final String mask;
public MaskWatcher(String mask) {
this.mask = mask;
}
public static MaskWatcher buildCpf() {
return new MaskWatcher("###.###.###-##");
}
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
isDeleting = count > after;
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if (isRunning || isDeleting) {
return;
}
isRunning = true;
int editableLength = editable.length();
if (editableLength < mask.length()) {
if (mask.charAt(editableLength) != '#') {
editable.append(mask.charAt(editableLength));
} else if (mask.charAt(editableLength-1) != '#') {
editable.insert(editableLength-1, mask, editableLength-1, editableLength);
}
}
isRunning = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment