Format credit card in edit text in android

后端 未结 29 2031
耶瑟儿~
耶瑟儿~ 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:49

     private class TextWatcherIBAN implements TextWatcher {
    
            @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) {
                textInputEditText.removeTextChangedListener(this);
                formatIBANEditText(textInputEditText);
                textInputEditText.addTextChangedListener(this);
    
            }
        }
    
    
    public void formatIBANEditText(TextInputEditText editText) {
        String decimalAmount = editText.getText().toString();
        int selection = editText.getSelectionEnd() == decimalAmount.length() ? -1 : editText.getSelectionEnd();
        decimalAmount = formatIBAN(decimalAmount);
        editText.setText(decimalAmount);
    
        if (selection != -1) {
            editText.setSelection(selection);
        } else {
            editText.setSelection(decimalAmount.length());
        }
    
    }
    
    public String formatIBAN(String text) {
        return formatterIBAN(new StringBuilder(text));
    }
    
    private String formatterIBAN(StringBuilder text) {
        int group = text.toString().length() / 5;
        int spaceCount = getSpaceCount(text);
        if (spaceCount < group) {
            return formatterIBAN(text.insert(4 + 5 * spaceCount, space));
        } else {
            return text.toString();
        }
    }
    
    private int getSpaceCount(StringBuilder text) {
        int spaceCount = 0;
        for (int index = 0; index < text.length(); index++) {
            if (text.charAt(index) == space.charAt(0)) {
                spaceCount++;
            }
        }
        return spaceCount;
    }
    
    
    textInputEditText.addTextChangedListener(new TextWatcherIBAN());
    

提交回复
热议问题