首页 > 解决方案 > TextWatcher 中 afterTextChanged 中的 setText 使退格键不起作用

问题描述

我正在使用addTextChangedListener(myTextWatcher)editText的一些货币格式。我的setText()里面有。afterTextChangedTextWatcher

  public void afterTextChanged(Editable s) {
        et.removeTextChangedListener(this);

        (snipped)
        et.setText(someText);
        (snipped)

        et.addTextChangedListener(this);
    }

在此处输入图像描述 问题是即使按住退格键我也只能删除一个字符。我发现setTextafterTextChanged使退格键不起作用的情况下。我不知道确切的机制,但它似乎setText推动了退格。

此外,这似乎不会在 Android 7.0 中发生,而是在 android 8.0 和 9.0 中发生。

先感谢您!

标签: android

解决方案


使用它来了解何时按下退格键:

editText.setOnKeyListener(new OnKeyListener() {                 
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    //You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
    if(keyCode == KeyEvent.KEYCODE_DEL) {  
        editText.setText(editText.getText().tostring()); // gets the current text and sets it again
    }
    return false;       
}
});

你说它只工作一次。通过这样做,如果您按下它,它会给您再次设置文本的机会,然后您只能再次按下退格键。


推荐阅读