How to disable horizontal scrolling in Android webview

Here is how I disable horizontal scrolling only for a webview.

webView.setHorizontalScrollBarEnabled(false);
webView.setOnTouchListener(new View.OnTouchListener() {
    float m_downX;
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getPointerCount() > 1) {
            //Multi touch detected
            return true;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                // save the x
                m_downX = event.getX();
                break;
            }
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP: {
                // set x so that it doesn't move
                event.setLocation(m_downX, event.getY());
                break;
            }

        }
        return false;
    }
});

Basically intercept the touch event and don't allow the x value to change. This allows the webview to scroll vertically but not horizontally. Do it for y if you want the opposite.


This is a hack, but one that has worked for me successfully in the past. Surround your WebView in a vertically oriented ScrollView:

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"    >
  <WebView
    android:id="@+id/mywebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</ScrollView>

and then disable all scrolling in your WebView.

To disable your WebView's scrolling, you can use this code:

 // disable scroll on touch
webview.setOnTouchListener(new View.OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
});