Skip to content

Instantly share code, notes, and snippets.

@Sefford
Created January 27, 2015 11:15
Show Gist options
  • Save Sefford/b9d63c7d6ed262a4b8dd to your computer and use it in GitHub Desktop.
Save Sefford/b9d63c7d6ed262a4b8dd to your computer and use it in GitHub Desktop.
Credit Card Watcher
package com.feverup.fever.ui.textwatchers;
/**
* Created by sefford on 14/02/14.
*/
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
/**
* Formats the watched EditText to a credit card number
*/
public class FourDigitCardFormatWatcher implements TextWatcher {
// Change this to what you want... ' ', '-' etc..
static final char SPACE = ' ';
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Empty
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Empty
}
@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 <= 4) {
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