Created
April 13, 2018 06:59
-
-
Save hasankucuk/89ab038fbe2cd5ec124e77447bd42f2c to your computer and use it in GitHub Desktop.
FourDigitCardFormatWatcher for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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