Detect backspace in TextWatcher [duplicate]

假装没事ソ 提交于 2019-11-28 03:16:23

问题


This question already has an answer here:

  • Android EditText delete(backspace) key event 17 answers

I am using TextWatcher and I am unable to detect Backspace key in TextWatcher.afterTextChange event. I also want to clear textView on some condition in textWatcher event.

public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    // I want to detect backspace key here
}

回答1:


A KeyListener can fulfil both of your conditions.

mEditText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
           if(keyCode == KeyEvent.KEYCODE_DEL){  
             //on backspace
             }
    return false        
        }
});

Similarly inside the onKey(), you can put multiple check statements to check for the condition, when you would want to clear the textView.

EDIT : As @RankoR was kind enough to point out, please bear in mind that onKeyListener() works only for the hardware keyboards and not the soft keyboards.




回答2:


To detect a backspace in TextWatcher, you can check the variable count that is passed into the onTextChange function (count will be 0 if a backspace was entered), like this:

@Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {

  if (react) {
    if (count == 0) {
      //a backspace was entered
    }

    //clear edittext
    if(/*condition*/) {
      react = false;
      setText("");
      react = true;
    }
  }
}

The react boolean is needed for the setText() function otherwise it becomes recursive. Hope this helps!



来源:https://stackoverflow.com/questions/12202047/detect-backspace-in-textwatcher

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