Automatically add dash in phone number in Android

前端 未结 7 2330
-上瘾入骨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条回答
  •  轮回少年
    2020-12-17 21:33

    Thanks for the all above answer.

    • The editText.setOnKeyListener() will never invoke when your device has only soft keyboard.
    • If we strictly follow the rule to add "-", then this code not always show desire result.

      editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

    but above code is best solution for formatting phone no.

    Apart from above this solution, I write a code which work on all types of condition::

    phoneNumber.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) {
                if (len > phoneNumber.getText().length() ){
                    len--;
                    return;
                }
                len = phoneNumber.getText().length();
    
                if (len == 4 || len== 8) {
                    String number = phoneNumber.getText().toString();
                    String dash = number.charAt(number.length() - 1) == '-' ? "" : "-";
                    number = number.substring(0, (len - 1)) + dash + number.substring((len - 1), number.length());
                    phoneNumber.setText(number);
                    phoneNumber.setSelection(number.length());
                }
            }
        });
    

    this line of code required to add "-" on 3rd & 6th position of number. if (len == 4 || len== 8)

提交回复
热议问题