Preethi Preethi - 1 year ago 189
Android Question

Format credit card in edit text in android

How to make

accept input in format:

4digit 4digit 4digit 4digit

I tried Custom format edit text input android to accept credit card number, but unfortunately I was unable to delete the spaces. Whenever there is a space, I could not to delete it. Please help me in finding out the issue.

Answer Source

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 = ' ';

    public void onTextChanged(CharSequence s, int start, int before, int count) {

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download