I have two EditText (each only only accepts one character) and I want to handle both fields like I had only one.
I'm using a TextWatcher to set the focus in the second one when the user writes a character in the first one, but I don't know how to do the opposite.
If the user press the delete button in the second EditText (being this EditText empty) I want to move the focus to the first EditText and delete the character there.
The problem is that TextWatcher doesn't work when the user tries to delete an empty field (because in fact nothing is changing). And onKeyDown event only works with hard keyboards so I don't have any idea of how to deal with this problem...
Thanks!
Possible duplicate of Android EditText delete(backspace) key event
just checked the code from that question (which actually come from the provided question and answered by Labeeb P) with the test project with just two edits on layout and it seems to work just fine - I'm able to receive delete even if edit is empty.
Seems android documentation of EditText should be made more clear or at least any guide for EditText - Soft Keyboard interaction provided, because there many typical ones whose should be worked out by nearly every developer.
UPDATE: Seems this way doesn't work on latest (at least after 4.1) Android versions. This answer seems to work on versions after 4.1.
A simpler solution to this that I stumbled upon is using an InputFilter. InputFilter's
filter()
method appears to report all soft keyboard events - even those where the EditText's value isn't changing.So to address your specific situation, construct an input filter and set accordingly:
Backspace events can be evaluated using
end
,dStart
, anddEnd
.dStart
will always be less thandEnd
if a character was deleted. If theEditText
is empty, you can still evaluate backspace presses by checking ifend
== 0.Note that bulk deletes will also be caught in this
if
statement, so you may want to do some extra checking withingfilter()
. Also note that if you're using your computer keyboard to type into EditTexts in emulators, you can get unexpected results. Best to click software buttons for testing.I achieved it by overriding
EditText
in order to get access toInputConnection
object which containsdeleteSurroundingText
method. It helps to detect deletion (backspace) event. Please, take a look at a solution I provided there: Android - cannot capture backspace/delete press in soft. keyboardThis solution works properly for both hardKeyboard and softKeyboard.
Use the Extension provided at, https://github.com/ciasaboark/Android-Shell/blob/master/src/com/example/com/programmingthetux/tutorial/ZanyEditText.java
Now you can use it in your Activity like so: