Search code examples
androidandroid-webview

WebView onKeyListener not working


I have to intercept the touch on the screen, and this is my code:

    mWebView = findViewById(R.id.webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(URL);
    mWebView.setOnTouchListener(this);
    mWebView.setOnKeyListener(this);

and my listeners:

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
        Log.i(TAG, "Hello, touch.");
        onTouchEvent();
        return false;
    }
    return false;
}

@Override
public boolean onKey(View view, int i, KeyEvent keyEvent)
{
    Log.i(TAG, "Hello, onKey.");
    onTouchEvent();
    return false;
}

While the on touch is working fine for touches on the screen, it dosen't intercept the touch event on the keyboard. For this reason, I've added the onkeylistener, but it's not intercepting the key events. As last thing, I don't care about what is typed, but just if the screen has been touched.


Solution

  • why not trying onkeyDown?

     @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack()){
                    webView.goBack();
                }else{
                    finish();
                }
                return true;
            }
    
        }
        return super.onKeyDown(keyCode, event);
    }
    

    OR

    override this method --> onUnhandledKeyEvent (WebView view, KeyEvent event)

    more details on:

    https://developer.android.com/reference/android/webkit/WebViewClient.html#onUnhandledKeyEvent(android.webkit.WebView,%20android.view.KeyEvent)

    OR

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        boolean dispatchFirst = super.dispatchKeyEvent(event);
        // Listening here for whatever key events you need
        if (event.getAction() == KeyEvent.ACTION_UP)
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_SPACE:
                case KeyEvent.KEYCODE_ENTER:
                    // e.g. get space and enter events here
                    break;
            }
        return dispatchFirst;
    }
    

    NOTE:-

    Preventing developers from accessing the events by default was made by Googlers on purpose. Because the key event input isn't the only one anymore. There're gestures, voice and more is coming. Official recommendation is to "stop relying on legacy key events for text entry at all". Check out more details here: https://code.google.com/p/android/issues/detail?id=42904#c15