Mask an EditText with Phone Number Format NaN like in PhoneNumberUtils

后端 未结 8 1266
广开言路
广开言路 2020-12-05 05:08

I want to make user inputted phone number in an editText to dynamically change format every time the user inputs a number. That is, when user inputs up to 4 digits, like 714

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 05:18

    This code allow you enter phone number with mask ### - ### - #### (without spaces) and also here is fixed the issue with deletion of phone digits:

    editText.addTextChangedListener(new TextWatcher() {
                final static String DELIMITER = "-";
                String lastChar;
    
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    int digits = editText.getText().toString().length();
                    if (digits > 1)
                        lastChar = editText.getText().toString().substring(digits-1);
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    int digits = editText.getText().length();
                    // prevent input dash by user
                    if (digits > 0 && digits != 4 && digits != 8) {
                        CharSequence last = s.subSequence(digits - 1, digits);
                        if (last.toString().equals(DELIMITER))
                            editText.getText().delete(digits - 1, digits);
                    }
                    // inset and remove dash
                    if (digits == 3 || digits == 7) {
                        if (!lastChar.equals(DELIMITER))
                            editText.append("-"); // insert a dash
                        else
                            editText.getText().delete(digits -1, digits); // delete last digit with a dash
                    }
                    dataModel.setPhone(s.toString());
                }
    
                @Override
                public void afterTextChanged(Editable s) {}
            });
    

    Layout:

    
    

提交回复
热议问题