How can I detect delete (backspace) key event for a editText? I've tried using TextWatcher, but when the editText is empty, when I press delete key, nothing happens. I want to detect delete key press foe an editText even if it has no text.

解决方案

NOTE:onKeyListener doesn't work for soft keyboards

You can set OnKeyListener for you editText so you can detect any key press

EDIT: A common mistake we are checking KeyEvent.KEYCODE_BACK for backspace, but really it is KeyEvent.KEYCODE_DEL (Really that name is confusioning! )

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){

//this is for backspace

}

return false;

}

});

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐