在 EditText afterTextChanged() 方法中避免退格

Avoiding backspace in EditText afterTextChanged() method

所以,我已经实现了一个简单的替换方法,可以替换文本更改之前的字符。

 @Override
 public void afterTextChanged(Editable s) {

     editText.removeTextChangedListener(this);

     if (s.length() == 0)
       return;
       s.replace(editText.getSelectionStart(),editText.getSelectionStart()+1,"PP");

     editText.addTextChangedListener(this);
}

因为这对所有类型的文本更改都有效,它添加了 "PP" 即使我按下后退 space 按钮。有什么办法可以排除 backspace 吗?

您可以使用全局布尔变量,它会告诉您是否应该执行 afterTextChanged() 中的代码。

为此,您应该将 View.onKeyListener() 添加到 editText 并在其中添加 thatBooleanVariable = keyCode != KeyEvent.KEYCODE_DEL; 如果单击退格键,它将 return false。

之后,用 if (thatBooleanVariable) { }.

包裹 afterTextChanged() 中的所有内容

首先检测是否按下退格键

然后在按下退格键时避免替换

editText.addTextChangedListener(new TextWatcher() {

        //Normally assume that Backspace not pressed 
        boolean isNotBackspace = true;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //if current count is grater then before that means char added
            //So if current count is smaller then before that means backspace pressed 
            isNotBackspace = count>before;
        }

        @Override
        public void afterTextChanged(Editable s) {

            editText.removeTextChangedListener(this);
            Log.e("isNotBackButton", isNotBackButton+"");

            if (s.length() == 0) {
                //Edit is here 
                //return; //need to block return; because this preventing
                //from adding  adding addTextChangedListener
                isNotBackButton = true;
            //if not backspace pressed then proceed else no action 
            }else if(isNotBackButton){
                s.replace(editText.getSelectionStart(), editText.getSelectionEnd(), "PP");
            }

            editText.addTextChangedListener(this);

        }
 });