android format edittext to display spaces after every 4 characters

前端 未结 12 1711
傲寒
傲寒 2020-12-10 13:27

Android - I want to get a number input from the user into an EditText - it needs to be separated by spaces - every 4 characters. Example: 123456781234 -> 1234 5678 1234

12条回答
  •  我在风中等你
    2020-12-10 13:43

    cleaner version of @Ario's answer which follows the DRY principle:

    private int prevCount = 0;
    private boolean isAtSpaceDelimiter(int currCount) {
        return currCount == 4 || currCount == 9 || currCount == 14;
    }
    
    private boolean shouldIncrementOrDecrement(int currCount, boolean shouldIncrement) {
        if (shouldIncrement) {
            return prevCount <= currCount && isAtSpaceDelimiter(currCount);
        } else {
            return prevCount > currCount && isAtSpaceDelimiter(currCount);
        }
    }
    
    private void appendOrStrip(String field, boolean shouldAppend) {
        StringBuilder sb = new StringBuilder(field);
        if (shouldAppend) {
            sb.append(" ");
        } else {
            sb.setLength(sb.length() - 1);
        }
        cardNumber.setText(sb.toString());
        cardNumber.setSelection(sb.length());
    }
    
    ccEditText.addTextChangedListener(new 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) {
            String field = editable.toString();
            int currCount = field.length();
    
            if (shouldIncrementOrDecrement(currCount, true)){
                appendOrStrip(field, true);
            } else if (shouldIncrementOrDecrement(currCount, false)) {
                appendOrStrip(field, false);
            }
            prevCount = cardNumber.getText().toString().length(); 
        } 
    }); 
    

提交回复
热议问题