I want to catch the backspace/delete button event in soft keyboard on EditText
custom.
How can I do it ?
I tried these solutions but they do not work for me :
Android custom EditText and back button override
Get back key event on EditText
Android EditText delete(backspace) key event
Thanks for your help !
EDIT : I found a fix for that isssue with the function DispatchKeyEvent :
@Override public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
// ...
}
return super.dispatchKeyEvent(event);
}
I found a fix for that isssue with the function DispatchKeyEvent :
Please, take a look at a solution I provided in another similar topic: Android - cannot capture backspace/delete press in soft. keyboard. You need to build your custom
EditText
class and overrideonCreateInputConnection
method in it. It will give you access todeleteSurroundingText
event which is firing when you click backspace. I've tested it in some devices and hope it will work in others also. Try it and give a feedback.Here you go..
Catching Key Events from soft input methods in Android is unreliable. Here is an excerpt from the JavaDoc for the
KeyEvent
class:One workaround could involve using
TextWatcher
. Whenever a delete occurs in anEditText
, the character count drops.Edit: This is untested, so may not be completely reliable. In addition, it's worth pointing out that
count
may also read0
if a long section of text is selected and then replaced. I created a library once that was designed to add Undo/Redo functionality toEditText
, but can alsoidentify the difference between text being replaced and deleted
, so this may be of use to you if you require more accuracy.