Android passing touch event to WebView's inner content

pat picture pat · Oct 28, 2013 · Viewed 14.4k times · Source

I have a webview that I'm setting an onTouchListener on in order to capture swipe events on the actual view.

I also set a WebViewClient on the WebView in order to override Url Loading when clicking on certain links inside the webview.

The problem is the OnTouch handler always receives the action first and even if I return false (when not a swipe) it does not pass the touch event to the inner html content and thus the link is never actually clicked. If I remove the onTouchListener it works fine. Is it possible to pass the touch event to the content somehow?

Answer

ripopenid picture ripopenid · Oct 29, 2013

You need to set, inside the main activity's OnCreate(), an OnTouchListener() with a requestFocus():

mWebView = (MyWebView) findViewById(R.id.webview);

mWebView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
        }
        return false;
    }
});