Search code examples
androidwebview

Android webview not emitting all key events


I have a simple android activity that overrides onKeyDown and onKeyUp. All key events trigger correctly.

When I add a webview and use setOnKeyListener, only a subset of the key events are triggered compared to the activity onKeyUp and onKeyDown handlers. The webview only triggers certain keys like volume up, volume down, menu, back. It fails to trigger for page up, page down, left, right, up, down, select.

I have tried extending WebView and overriding onCreateInputConnection to return a BaseInputConnection per some other posts but it has no effect.


Solution

  • This is because webView is consuming those key events. You can override the keyEvents before they are being consumed by WebView with something like this

       webView.webViewClient = object : WebViewClient() {
                    override fun shouldOverrideKeyEvent(view: WebView?, event: KeyEvent?): Boolean {
                        // Handle key events here
                        return super.shouldOverrideKeyEvent(view, event)
                    }
                }