用户开始键入后如何在EditText中添加字符

时间:2018-07-24 18:36:51

标签: android android-edittext

我有一个editText,用户在其中输入电话号码,但是当他们单击其第一个数字时,我希望在文本的开头出现一个“ +”。我有此代码,但“ +”一直存在。我只希望它在用户输入数字时出现,我该如何解决?

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

3 个答案:

答案 0 :(得分:0)

使用TextWatcher

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

像这样实现。您也可以欺骗它以满足您的需求

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

或者,您可以使用OnEditorActionListener接口来避免匿名内部类。

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

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