Skip to content

Instantly share code, notes, and snippets.

@hasankucuk
Created April 13, 2018 06:59
Show Gist options
  • Save hasankucuk/89ab038fbe2cd5ec124e77447bd42f2c to your computer and use it in GitHub Desktop.
Save hasankucuk/89ab038fbe2cd5ec124e77447bd42f2c to your computer and use it in GitHub Desktop.
FourDigitCardFormatWatcher for Android
mEdtPaymentCreditNumber.addTextChangedListener(new FourDigitCardFormatWatcher());
public static class FourDigitCardFormatWatcher implements TextWatcher {
private static final char space = ' ';
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
// Remove spacing char
if (s.length() > 0 && (s.length() % 5) == 0) {
final char c = s.charAt(s.length() - 1);
if (space == c) {
s.delete(s.length() - 1, s.length());
}
}
// Insert char where needed.
if (s.length() > 0 && (s.length() % 5) == 0) {
char c = s.charAt(s.length() - 1);
// Only if its a digit where there should be a space we insert a space
if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) {
s.insert(s.length() - 1, String.valueOf(space));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment