Automatically add dash in phone number in Android

前端 未结 7 2342
-上瘾入骨i
-上瘾入骨i 2020-12-17 21:18

Instead of 5118710, it should be 511-8710. I\'d like to add a dash after the user the user inputted 3 digits already in the EditText. The maximum length of

7条回答
  •  猫巷女王i
    2020-12-17 21:42

    I have a few small changes to the solution of neo108 so it can work with both soft keyboard and hard keyboard, in my code for example the edittext will follow the rule to automatically add " " at position 5 and 9.

    txtPhone.addTextChangedListener(new TextWatcher() {
    
            int keyDel;
    
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                txtPhone.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                        if (keyCode == KeyEvent.KEYCODE_DEL) {
                            keyDel = 1;
                        }
                        return false;
                    }
                });
    
                String currentString = txtPhone.getText().toString();
                int currentLength = txtPhone.getText().length();
    
                if (currentLength == 5 || currentLength == 9) {
                    keyDel = 1;
                }
    
                if (keyDel == 0) {
                    if (currentLength == 4 || currentLength == 8) {
                        txtPhone.setText(txtPhone.getText() + " ");
                        txtPhone.setSelection(txtPhone.getText().length());
                    }
                } else {
                    if (currentLength != 5 && currentLength != 9) {
                        keyDel = 0;
                    } else if ((currentLength == 5 || currentLength == 9)
                            && !" ".equals(currentString.substring(currentLength - 1, currentLength))) {
                        txtPhone.setText(currentString.substring(0, currentLength - 1) + " "
                                + currentString.substring(currentLength - 1, currentLength));
                        txtPhone.setSelection(txtPhone.getText().length());
                    }
                }
            }
    

提交回复
热议问题