Jay Gajjar Jay Gajjar - 1 year ago 284
Android Question

Detect backspace in TextWatcher

I am using

and I am unable to detect Backspace key in
event. I also want to clear
on some condition in

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

Answer Source

A KeyListener can fulfil both of your conditions.

mEditText.setOnKeyListener(new OnKeyListener() {                 
    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.