How to add a character in EditText after user starts typing

后端 未结 3 1959
余生分开走
余生分开走 2021-01-26 16:54

I have an editText where a user inputs a phone number, but right when they click their first number, I want a \'+\' to appear in the beginning of the text. I have this code but

3条回答
  •  日久生厌
    2021-01-26 17:16

        Pattern p = Pattern.compile("^\\d+.*");
    
    editText.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }
    
            @Override
            public void afterTextChanged(Editable s) {
                if (p.matcher(s.toString().trim()).matches()) {
                    editText.setText(prefix + s.toString());
                }
                Selection.setSelection(editText.getText(), editText.getText().length());
            }
        });
    

提交回复
热议问题