androidandroid-softkeyboardcustom-keyboardime

Doesn't work key "delete" in ime android keyboard


I have finished my ime custom keyboard. But I have some problems. When I type something into first textField and than try to type into second textField I can't delete anything into secon textfield.

This is code of my keybutton

 val currentInputConnection = (context as IMEService).currentInputConnection
        
"delete" -> {
            CoroutineScope(Dispatchers.Main).launch {
                while (motionEvent.action == MotionEvent.ACTION_DOWN) {
                    currentInputConnection.sendKeyEvent(
                        KeyEvent(
                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL
                        )
                    )
                }
            }
        }

What I need to do to fix it? image - this is my example.

I expect that key "delete" will work into any textfield. Now when I try to move to second textfield I can't delete any digitals or letter.


Solution

  • Don't send a key event. You should almost never send key events from a keyboard (the one exception is if the type of the input is NULL, then sometimes this will cause it to work if the author of the connected custom view didn't know what they were doing). Use deleteSurroundingText instead. Similarly, you should be using commitText for sending text, not sending key events.

    Also you should probably not be doing this on a coroutine. Sending data down the input connection asynchronously risks issues if the connection is torn down between now and the coroutine firing- for example if a second text field is tapped and a new input connection is created. This code may or may not be safe (depends on where it's being called, and if its possible for currentInputConnection to change), but generally the InputConnection is meant to be used synchronously.