Phone number formatting an EditText in Android

前端 未结 14 952
情深已故
情深已故 2020-12-02 12:03

I am making a simple Address Book app (targeting 4.2) that takes name, address, city, state, zip and phone.

I want to format the phone number input as a phone number

14条回答
  •  清歌不尽
    2020-12-02 12:31

    //(123) 456 7890  formate set
    
    private int textlength = 0;
    
    public class MyPhoneTextWatcher implements TextWatcher {
    
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
    
            String text = etMobile.getText().toString();
            textlength = etMobile.getText().length();
    
            if (text.endsWith(" "))
                return;
    
            if (textlength == 1) {
                if (!text.contains("(")) {
                    etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                    etMobile.setSelection(etMobile.getText().length());
                }
    
            } else if (textlength == 5) {
    
                if (!text.contains(")")) {
                    etMobile.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                    etMobile.setSelection(etMobile.getText().length());
                }
    
            } else if (textlength == 6 || textlength == 10) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
    
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    }
    

提交回复
热议问题