Format credit card in edit text in android

After finding multiple answers that are ‘OK’. I moved towards a better TextWatcher which is designed to work correctly and independently from the TextView.

TextWatcher class is as follows:

/**
 * Formats the watched EditText to a credit card number
 */
public static class FourDigitCardFormatWatcher implements TextWatcher {

    // Change this to what you want... ' ', '-' etc..
    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));
            }
        }
    }
}

Then add it to your TextView as you would any other TextWatcher.

{
  //...
  mEditTextCreditCard.addTextChangedListener(new FourDigitCardFormatWatcher()); 
}

This will auto delete the space sensibly going back so the user can actually do less keystrokes when editing.

Caveat

If you are using inputType="numberDigit" this will disable the ‘-‘ and ‘ ‘ chars, so I recommend using, inputType="phone". This enables other chars, but just use a custom inputfilter and problem solved.

Leave a Comment