How to add a character in EditText after user starts typing

蹲街弑〆低调 提交于 2019-12-02 20:27:56

问题


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 the '+' is constantly there. I only want it to appear when a user inputs a number, how would I fix this?

    final EditText editText = findViewById(R.id.register_edit_phone);
    final String prefix = "+";
    editText.setText(prefix);
    Selection.setSelection(editText.getText(), editText.getText().length());
    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 (!s.toString().startsWith(prefix)) {
                editText.setText(prefix);
                Selection.setSelection(editText.getText(), editText.getText().length());
            }
        }
    });

回答1:


Use TextWatcher

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

Implement it like this. You can also trick it to fit your needs

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            // Specify your database function here.
            return true;
        }
        return false;
    }
});

Alternatively, you can use the OnEditorActionListener interface to avoid the anonymous inner class.




回答2:


    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());
        }
    });



回答3:


    if (s.length == 1){ 
          if (s.toString().equals("+"))  editText.setText""
          else editText.setText("+"+s.toString)
          }


来源:https://stackoverflow.com/questions/51505462/how-to-add-a-character-in-edittext-after-user-starts-typing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!