Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android passing touch event to WebView's inner content

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?

like image 615
pat Avatar asked Feb 14 '23 20:02

pat


2 Answers

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;
    }
});
like image 168
ripopenid Avatar answered Mar 06 '23 10:03

ripopenid


Don't use the OnTouchListener, but instead override OnTouchEvent in your WebView:

@Override
public boolean onTouchEvent(MotionEvent event) {

    // do your stuff here... the below call will make sure the touch also goes to the webview.

    return super.onTouchEvent(event);
}
like image 38
Frank Avatar answered Mar 06 '23 10:03

Frank