152

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • There is a similar question in the Stackoverflow. You need to override `EditText` in order to get access to `InputConnection` object which contains `deleteSurroundingText` method. It will help you to detect deletion (backspace) event. Please, take a look at a solution I provided there [Android - cannot capture backspace/delete press in soft. keyboard][1] [1]: https://stackoverflow.com/a/34857618/1808829 – Ayaz Alifov Jan 26 '23 at 09:33

16 Answers16

212

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 very confusing! )

editText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        //You can identify which key pressed by checking keyCode value with KeyEvent.KEYCODE_
        if(keyCode == KeyEvent.KEYCODE_DEL) {  
            //this is for backspace
        }
        return false;       
    }
});
Boken
  • 4,825
  • 10
  • 32
  • 42
Labeeb Panampullan
  • 34,521
  • 28
  • 94
  • 112
  • 13
    i just tried it, but onKeyListeners apparently do not register backspaces. – stefs Jun 30 '11 at 13:00
  • 8
    It will not work for soft keyboard. This will only work for hardware input. – Varundroid Apr 05 '14 at 22:28
  • 6
    On my Nexus4 (running stock KitKat) this *does* work for the software keyboard. – Matthias May 01 '14 at 21:52
  • As a matter a fact it also works with the soft keyboard on my Samsung Galaxy Xcover (running v2.3.6/Gingerbread) – Matthias May 01 '14 at 21:58
  • what is the way to do for soft keyboards onKeyListener- "@Estel" – SubbaReddy PolamReddy Jul 02 '14 at 06:51
  • Hi, on my HTC m7 it's work with system keyboard and SwiftKey but doesn't work with new Google Keyboard. I detect also this problem on Samsung S3 and Swype keyboard. Any work solutions for that? – Eliasz Kubala Nov 14 '14 at 07:06
  • 19
    SO if it doesnt work for soft keys, then why is this answer accepted in/under android platform.. – DJphy Jun 10 '15 at 05:54
  • Confirmed that this does NOT work for soft keyboard in Android 5.1 on Nexus 5. – vwmattr Jun 19 '15 at 18:40
  • 47
    use `event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL` if you dont want to event to fire twice per press of backspace – Fonix Aug 15 '16 at 04:27
  • Confirmed working on Samsung Galaxy S6 Edge running 6.0.1 and Nexus 5 running 6.0.1 – MichaelStoddart Oct 25 '16 at 09:28
  • 2
    According to https://developer.android.com/reference/android/view/View.OnKeyListener.html , do not use this method to detect soft keyboard key change. – Cheok Yan Cheng Mar 22 '18 at 18:46
  • Use TextWatcher() isntaed https://stackoverflow.com/a/65574180/8663316 – Faizan Haidar Khan Jan 05 '21 at 06:33
  • From official Google's documentation `Key presses in software keyboards will generally NOT trigger this method, although some may elect to do so in some situations.` source: https://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey(android.view.View,%20int,%20android.view.KeyEvent) – Oz Shabat Apr 20 '22 at 09:54
92

It's been a while since you asked but I just had the same issue. As already mentioned by Estel the problem with key listeners is that they only work with hardware keyboards. To do this with an IME (soft keyboard), the solution is a bit more elaborate.

The single method we actually want to override is sendKeyEvent in the EditText's InputConnection class. This method is called when key events occur in an IME. But in order to override this, we need to implement a custom EditText which overrides the onCreateInputConnection method, wrapping the default InputConnection object in a proxy class! :|

Sounds complicated, but here's the simplest example I could contrive:

public class ZanyEditText extends EditText {

    private Random r = new Random();

    public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ZanyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ZanyEditText(Context context) {
        super(context);
    }

    public void setRandomBackgroundColor() {
        setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
                .nextInt(256)));
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class ZanyInputConnection extends InputConnectionWrapper {

        public ZanyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                ZanyEditText.this.setRandomBackgroundColor();
                // Un-comment if you wish to cancel the backspace:
                // return false;
            }
            return super.sendKeyEvent(event);
        }

    }

}

The line with the call to setRandomBackgroundColor is where my special backspace action occurs. In this case, changing the EditText's background colour.

If you're inflating this from XML remember to use the full package name as the tag:

<cc.buttfu.test.ZanyEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/somefield"
></cc.buttfu.test.ZanyEditText>
Idris
  • 1,887
  • 1
  • 14
  • 9
  • 28
    I recently ran into the same issue on Jelly Bean. I found that this solution mostly worked, except that I had to override deleteSurroundingText(...) instead of sendKeyEvent(...) (which was not being called at all). Hope this helps someone else! – Brandon Sep 26 '12 at 14:01
  • This answer, combined with @Brandon comment above got this working for me. What I'm wondering now is, how this will work on pre-JellyBean devices. – Christopher Perry Jan 13 '13 at 00:23
  • It does work with the accepted answer on 2.2 and 2.3 devices for me. – Christoph Apr 11 '13 at 15:37
  • seems like it's firing the key event for backspace twice on 2.3... :/ – Jeff May 15 '13 at 14:28
  • There are two separate bugs affecting the LatinIME keyboard that can prevent generation of KEYCODE_DEL events. If you read my answer below it will explain what is going on with each of these issues, and how to get around them both. The solution includes code: http://stackoverflow.com/questions/18581636/android-cannot-capture-backspace-delete-press-in-soft-keyboard/19980975#19980975 – Carl Jan 17 '14 at 04:34
  • This solution works really well for me, thank you! But there is one situation in which it does not work - when the user has highlighted text (i.e., getSelectionStart != getSelectionEnd). The sendKeyEvent method is not even called in that situation. I tried the below solution using deleteSurroundingText, but this method is not called if there is a selection either. This is in 4.2. Any ideas? – Sarah Feb 10 '14 at 23:56
  • 27
    This doesn't work when the edittext is empty, any ideas on how to get an event for the delete key when the edittext is empty and has no text? 4.2 – Rickster Apr 05 '14 at 09:13
  • Any way to bind this only to a specific EditText? – Alex Mar 16 '15 at 10:59
  • @jibruno I know this may be a bit late, but it may be that you're getting the event once for key down and once for key up (check event.getAction() for KeyEvent.ACTION_DOWN and ACTION_UP). – MCLLC Feb 05 '16 at 17:28
  • Is there any way to get delete key event on gboard handwriting input keyboard. (keyboard with one mic, gear icon and delete key). This method is working fine with gboard and handwriting keyboard. – arjunkn May 22 '18 at 05:56
76

This is just an addition to Idris's answer, adding in the override to deleteSurroundingText as well. I found more info on that here: Android: Backspace in WebView/BaseInputConnection

package com.elavon.virtualmerchantmobile.utils;

import java.util.Random;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.widget.EditText;

public class ZanyEditText extends EditText {

    private Random r = new Random();

    public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ZanyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ZanyEditText(Context context) {
        super(context);
    }

    public void setRandomBackgroundColor() {
        setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
                .nextInt(256)));
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class ZanyInputConnection extends InputConnectionWrapper {

        public ZanyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                ZanyEditText.this.setRandomBackgroundColor();
                // Un-comment if you wish to cancel the backspace:
                // return false;
            }
            return super.sendKeyEvent(event);
        }


        @Override
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {       
            // magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
            if (beforeLength == 1 && afterLength == 0) {
                // backspace
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                    && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
            }

            return super.deleteSurroundingText(beforeLength, afterLength);
        }

    }

}
Community
  • 1
  • 1
Jeff
  • 4,136
  • 23
  • 32
  • 3
    Thank you! The `deleteSurroundingText` bit was exactly what I needed after trying countless other solutions. – Adam Rosenfield Sep 17 '13 at 05:58
  • 5
    This solution has worked really well for me on previous Android versions, but unfortunately deleteSurroundingText is only called when removing whitespace on 4.4(KitKat). I have tested on both Nexus4 and 7. – Dean Dec 03 '13 at 18:21
  • 1
    it seems that deleteSurroundingText is required when EditText is multiline. Weird – Alex Sorokoletov Aug 02 '14 at 04:37
  • 8
    Thanks a ton man, didn't work with out deleteSurroundText. Android is so random that they should rename it to androm. – Torsten Ojaperv Apr 10 '15 at 13:20
  • 1
    For me just adding a KeyListener to the ZanyEditText in the enclosing fragment now registers key events. At least on Android M Preview. Its also worth noting here that if anyone is trying out this method and is also using the Design Support Library you need to extend AppCompatEditText. The reason for this is that the Design Support Library automatically replaces all instances of EditText in your layouts with the new version (all done in the background without your knowledge - to help with theme and style), but it can't replace custom classes like this. – Chris Jul 27 '15 at 18:45
  • @jibruno hey, I have implemented it, But In my case I have three Edittext, Now How Can I know that "On Which Edittext I have pressed DEL_KEY" ? – user5716019 Mar 28 '16 at 12:42
  • I'll be honest with you @user5716019 I haven't touched android code in 3 years. You should probably open a new question to ask that so you can get some attention on it. – Jeff Mar 28 '16 at 18:56
  • @jbruno Hi I have implemented the solution you suggested. But apparently I am getting the null pointer crash from this new implementation. Log is as follows java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.view.inputmethod.InputConnection.finishComposingText()' on a null object reference at android.view.inputmethod.InputConnectionWrapper.finishComposingText(InputConnectionWrapper.java:78) – Pruthviraj Apr 21 '16 at 08:02
  • 2
    It works for me, but I can't delete punctuation or spaces anymore! – Jason John Apr 22 '16 at 13:59
  • It works well for backspace, but when the text is multi-line it makes a copy of text in the previous line on hitting backspace. Any idea ,how to resolve this? – Nainal Aug 26 '17 at 06:46
  • 1
    Man, that helped me so tremendously. I had an ugly solution in place (with invisible character at the start) to detect backspaces at the beginning of a text, but that lead to issues with auto completion etc. This solution is much cleaner -- it does not work with API 19 though, but as Google Keep has the same issue with that version I suppose it is as good as it gets here. – Ridcully Sep 15 '17 at 09:02
  • line '// Un-comment if you wish to cancel the backspace: // return false;' is required to uncommented. By default event is being called twice if this does not return false. – Pankaj Kumar Apr 17 '18 at 11:54
  • 1
    FYI for anybody still using this. After the latest Gboard update (June 25th, 2018), this solution will cause strange behavior when attempting to delete text. Esp if the text has several periods. – Kachi Jul 04 '18 at 14:49
  • 1
    The above code will break for latest Gboard. To make the code workable in old and new Gboard, use `if (beforeLength == 1 && afterLength == 0 && ZanyEditText.this.getText().length() == 0) {` – Cheok Yan Cheng Sep 17 '18 at 15:42
27

Here is my easy solution, which works for all the API's:

private int previousLength;
private boolean backSpace;

// ...

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    previousLength = s.length();
}

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

@Override
public void afterTextChanged(Editable s) {
    backSpace = previousLength > s.length();

    if (backSpace) {

        // do your stuff ...

    } 
}

UPDATE 17.04.18 .
As pointed out in comments, this solution doesn't track the backspace press if EditText is empty (the same as most of the other solutions).
However, it's enough for most of the use cases.
P.S. If I had to create something similar today, I would do:

public abstract class TextWatcherExtended implements TextWatcher {

    private int lastLength;

    public abstract void afterTextChanged(Editable s, boolean backSpace);

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        lastLength = s.length();
    }

    @Override
    public void afterTextChanged(Editable s) {
        afterTextChanged(s, lastLength > s.length());
    }  
}

Then just use it as a regular TextWatcher:

 editText.addTextChangedListener(new TextWatcherExtended() {
        @Override
        public void afterTextChanged(Editable s, boolean backSpace) {
           // Here you are! You got missing "backSpace" flag
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Do something useful if you wish.
            // Or override it in TextWatcherExtended class if want to avoid it here 
        }
    });
Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
11

I sent 2 days to find a solution and I figured out a working one :) (on soft keys)

public TextWatcher textWatcher = new TextWatcher() {
@Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {   } 

@Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (count == 0) {
        //Put your code here.
        //Runs when delete/backspace pressed on soft key (tested on htc m8)
        //You can use EditText.getText().length() to make if statements here
        }
    }

@Override
    public void afterTextChanged(Editable s) {
    }
}

After add the textwatcher to your EditText:

yourEditText.addTextChangedListener(textWatcher);

I hope it works on another android devices too (samsung, LG, etc).

J.P
  • 135
  • 1
  • 2
6

My simple solution which works perfectly. You should to add a flag. My code snippet:

editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (after < count) {
                isBackspaceClicked = true;
            } else {
                isBackspaceClicked = false;
            }
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            if (!isBackspaceClicked) {
                // Your current code
            } else {
                // Your "backspace" handling
            }
        }
Neuron
  • 1,020
  • 2
  • 13
  • 28
3

Example of creating EditText with TextWatcher

EditText someEdit=new EditText(this);
//create TextWatcher for our EditText
TextWatcher1 TW1 = new TextWatcher1(someEdit);
//apply our TextWatcher to EditText
        someEdit.addTextChangedListener(TW1);

custom TextWatcher

public class TextWatcher1 implements TextWatcher {
        public EditText editText;
//constructor
        public TextWatcher1(EditText et){
            super();
            editText = et;
//Code for monitoring keystrokes
            editText.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if(keyCode == KeyEvent.KEYCODE_DEL){
                        editText.setText("");
                    }
                        return false;
                }
            });
        }
//Some manipulation with text
        public void afterTextChanged(Editable s) {
            if(editText.getText().length() == 12){
                editText.setText(editText.getText().delete(editText.getText().length() - 1, editText.getText().length()));
                editText.setSelection(editText.getText().toString().length());
            }
            if (editText.getText().length()==2||editText.getText().length()==5||editText.getText().length()==8){
                editText.setText(editText.getText()+"/");
                editText.setSelection(editText.getText().toString().length());
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {



        }
    }
2

for some one who's using Kotlin

addOnTextChanged is not flexible enought to handle some cases (ex: detect if user press delete when edit text was empty)

setOnkeyListener worked even soft keyboard or hardkeyboard! but just on some devices. In my case, it work on Samsung s8 but not work on Xiaomi mi8 se.

if you using kotlin, you can use crossline function doOnTextChanged, it's the same as addOnTextChanged but callback is triggered even edit text was empty.

NOTE: doOnTextChanged is a part of Android KTX library

  • 2
    You might probably specify that `doOnTextChanged ` extension function is accessible in Android KTX library – stone Dec 17 '19 at 07:55
  • 3
    But it seems that callback is NOT "triggered even edit text was empty". Could you please provide some snippet with the delete(backspace) interception for empty `EditText`? Thanks in advance – stone Dec 17 '19 at 08:50
  • 1
    ah, i have test it when i develop a project. In my case is on xiaomi mi8se, when edittext is empty and you press delete, no callback fired. I'll search for snippet for this sentence. – Mạnh Hoàng Huynh Dec 17 '19 at 09:05
1

Based on @Jiff ZanyEditText here is WiseEditText with setSoftKeyListener(OnKeyListener)

package com.locopixel.seagame.ui.custom;

import java.util.Random;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

public class WiseEditText extends AppCompatEditText {

    private Random r = new Random();
    private OnKeyListener keyListener;

    public WiseEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public WiseEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WiseEditText(Context context) {
        super(context);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new MyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class MyInputConnection extends InputConnectionWrapper {

        public MyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (keyListener != null) {
                keyListener.onKey(WiseEditText.this,event.getKeyCode(),event);
            }
            return super.sendKeyEvent(event);
        }

        @Override
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {       
            // magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
            if (beforeLength == 1 && afterLength == 0) {
                // backspace
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                    && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
            }

            return super.deleteSurroundingText(beforeLength, afterLength);
        }

    }

    public void setSoftKeyListener(OnKeyListener listener){
        keyListener = listener;
    }

}
Qamar
  • 4,959
  • 1
  • 30
  • 49
0

This seems to be working for me :

public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (before - count == 1) {
        onBackSpace();
    } else if (s.subSequence(start, start + count).toString().equals("\n")) {
        onNewLine();
    }
}
rocker99
  • 9
  • 2
0

I am also faced same issue in Dialog.. because I am using setOnKeyListener.. But I set default return true. After change like below code it working fine for me..

    mDialog.setOnKeyListener(new Dialog.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface arg0, int keyCode,
                             KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mDialog.dismiss();
                return true;
            }
            return false;//this line is important 

        }
    });
Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159
0

My problem was, that I had custom Textwatcher, so I didn't want to add OnKeyListener to an EditText as well as I didn't want to create custom EditText. I wanted to detect if backspace was pressed in my afterTextChanged method, so I shouldn't trigger my event.

This is how I solved this. Hope it would be helpful for someone.

public class CustomTextWatcher extends AfterTextChangedTextWatcher {

private boolean backspacePressed;

@Override
public void afterTextChanged(Editable s) {
    if (!backspacePressed) {
        triggerYourEvent();
    }
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    super.onTextChanged(s, start, before, count);
    backspacePressed = count == 0; //if count == 0, backspace is pressed
}
}
Dmitry Smolyaninov
  • 2,159
  • 1
  • 18
  • 32
-1

I have tested @Jeff's solution on version 4.2, 4.4, 6.0. On 4.2 and 6.0, it works well. But on 4.4, it doesn't work.

I found an easy way to work around this problem. The key point is to insert an invisible character into the content of EditText at the begining, and don't let user move cursor before this character. My way is to insert a white-space character with an ImageSpan of Zero Width on it. Here is my code.

                @Override
                public void afterTextChanged(Editable s) {
                    String ss = s.toString();
                    if (!ss.startsWith(" ")) {
                        int selection = holder.editText.getSelectionEnd();
                        s.insert(0, " ");
                        ss = s.toString();
                        holder.editText.setSelection(selection + 1);
                    }
                    if (ss.startsWith(" ")) {
                        ImageSpan[] spans = s.getSpans(0, 1, ImageSpan.class);
                        if (spans == null || spans.length == 0) {
                            s.setSpan(new ImageSpan(getResources().getDrawable(R.drawable.zero_wdith_drawable)), 0 , 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                }

And we need custom an EditText which has a SelectionChangeListener

public class EditTextSelectable extends android.support.v7.widget.AppCompatEditText {
public interface OnSelectChangeListener {
    void onSelectChange(int start, int end);
}

private OnSelectChangeListener mListener;

public void setListener(OnSelectChangeListener listener) {
    mListener = listener;
}

...constructors...

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    if (mListener != null) {
        mListener.onSelectChange(selStart, selEnd);
    }
    super.onSelectionChanged(selStart, selEnd);
}

}

And the last step

holder.editText.setListener(new EditTextSelectable.OnSelectChangeListener() {
                @Override
                public void onSelectChange(int start, int end) {
                    if (start == 0 && holder.editText.getText().length() != 0) {
                        holder.editText.setSelection(1, Math.max(1, end));
                    }
                }
            });

And now, we are done~ We can detect backspace key event when EditText has no actual content, and user will know nothing about our trick.

passerbywhu
  • 522
  • 5
  • 8
-1

This question may be old but the answer is really simple using a TextWatcher.

int lastSize=0;
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    //2. compare the old length of the text with the new one
    //3. if the length is shorter, then backspace was clicked
    if (lastSize > charSequence.length()) {
        //4. Backspace was clicked
        //5. perform action
    }
    //1. get the current length of of the text
    lastSize = charSequence.length();
}
BluRe.CN
  • 311
  • 2
  • 11
-2

Belated but it may help new visitors, use TextWatcher() instead will help alot and also it will work for both soft and hard keyboard as well.

 editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    //Here it means back button is pressed and edit text is now empty
                } else {
                   //Here edit text has some text
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
Faizan Haidar Khan
  • 1,099
  • 1
  • 15
  • 20
  • 2
    It will not work in every case, Suppose your editText is empty and the user pressed backspace? In that case, nothing will happen with the above solution as no text changed! – Intsab Haider Jul 19 '22 at 05:18
-3

You could set a key listener on the activity, and in the callback method, you could detect which key the user hit. The code below is for your reference. Hope it helps.

//after user hits keys, this method would be called.
public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (editText.isFocused()) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_DEL:  //delete key
                Log.i("INFO", "delete key hit"); //you should see this log in ddms after you hit delete key
                break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
Christopher Perry
  • 38,891
  • 43
  • 145
  • 187
Huang
  • 4,812
  • 3
  • 21
  • 20
  • Checked this solution - KEYCODE_DEL will be thrown to activity only if edit text will not handle this by itself. For example, when there is no text in editText, or there is some text, but cursor is at very beginning. Thats funny that in my case I need exactly that behavior – Anton Kizema Jun 24 '15 at 17:42
  • In my activity there is no EditText and I just make the keyboard appear programmatically. I need to catch every soft keyboard key and this seems the only working solution. The other one is overriding the dispatchKeyEvent method. Unfortunately starting from JellyBean the IME doesn't send a KeyEvent for DELETE key. http://developer.android.com/reference/android/view/KeyEvent.html – Bemipefe Sep 12 '15 at 11:05