Format credit card in edit text in android

后端 未结 29 2049
耶瑟儿~
耶瑟儿~ 2020-11-30 19:18

How to make EditText accept input in format:

4digit 4digit 4digit 4digit 

I tried Custom format edit text input android to acc

29条回答
  •  星月不相逢
    2020-11-30 19:42

    I just did the next implementation and works well for me, even with pasting and typing new text in any position of the EditText.

    Gist file

    /**
     * Text watcher for giving "#### #### #### ####" format to edit text.
     * Created by epool on 3/14/16.
     */
    public class CreditCardFormattingTextWatcher implements TextWatcher {
    
        private static final String EMPTY_STRING = "";
        private static final String WHITE_SPACE = " ";
        private String lastSource = EMPTY_STRING;
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            String source = s.toString();
            if (!lastSource.equals(source)) {
                source = source.replace(WHITE_SPACE, EMPTY_STRING);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < source.length(); i++) {
                    if (i > 0 && i % 4 == 0) {
                        stringBuilder.append(WHITE_SPACE);
                    }
                    stringBuilder.append(source.charAt(i));
                }
                lastSource = stringBuilder.toString();
                s.replace(0, s.length(), lastSource);
            }
        }
    
    }
    

    Usage: editText.addTextChangedListener(new CreditCardFormattingTextWatcher());

提交回复
热议问题