Android: Backspace in WebView/BaseInputConnection

Ok, finally figured this out.

In Android 4.2 (maybe in earlier versions as well) the backspace is not sent as a sendKeyEvent(..., KeyEvent.KEYCODE_DEL) by the standard soft keyboard. Instead, it is sent as deleteSurroundingText(1, 0).

So the solution in my case is to make a custom InputConnection with the following:

@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 super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
            && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
    }

    return super.deleteSurroundingText(beforeLength, afterLength);
}

Note: Please let me know if I am doing something stupid here, as it is my 3rd day writing for Android.

Leave a Comment