Jay Gajjar Jay Gajjar - 5 months ago 95
Android Question

Detect backspace in TextWatcher

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
}

Answer

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.

Comments