I made a custom keyboard for android. When I press backspace button of my keyboard I use
getCurrentInputConnection().deleteSurroundingText(1, 0);
to delete one letter from the input field. But when I select some text and then press the backspace button, the selected text is not deleted. What method in input connection should I use so that selected text is also deleted from my keyboard when I press the backspace button?
Call
getCurrentInputConnection().commitText("",1);
When deleting you need to take into account the following situations:
If there is a selection then it should be deleted. If there is no selection then the character in front of the cursor should be deleted.
Solution 1
At first I used this method. I like it because it only uses the input connection.
As long as the input connection is using the default
BaseInputConnection.deleteSurroundingText
method, this should be fine. However, it should be noted that the documentation warnsIf some custom view is using an input connection that doesn't correctly check for for text length or surrogate pairs, then this could cause a crash. Even though this is an unlikely senario, if you use this solution, then you should add that extra checking code here.
This may be why the sample Android keyboard first checks if there is a composing span, and if there isn't then it using the following solution.
Solution 2
You can also use the input connection to send a
KeyEvent
withKEYCODE_DEL
. In my opinion this is not as good because it is a soft keyboard masquerading as a hard keyboard. But many keyboards do this. When I was making a custom view that accepted keyboard input, I had to handle deletes as aKeyEvent
, that is, independently of the input connection (because the input connection was not deleting the text).So just send the delete message as a
KeyEvent
(as if you were pressing a hard keyboard key down and then letting it up).This works as expected. It will delete the selection if there is one, or delete one character behind the cursor if there isn't a selection. (However, you should handle any composing span separately.)
Thanks to this answer for the idea.