我知道它很晚,但我希望它会帮助某人,请使用下面提到的类来禁用水平滚动。
public class CustomWebView extends WebView implements View.OnTouchListener {
// the initial touch points x coordinate
private float touchDownX;
private OnScrollChangedCallback mOnScrollChangedCallback;
public CustomWebView(final Context context) {
super(context);
// make vertically scrollable only
makeVerticalScrollOnly();
}
public CustomWebView(final Context context, final AttributeSet attrs) {
super(context, attrs);
// make vertically scrollable only
makeVerticalScrollOnly();
}
public CustomWebView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
// make vertically scrollable only
makeVerticalScrollOnly();
}
@Override
protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
}
public OnScrollChangedCallback getOnScrollChangedCallback() {
return mOnScrollChangedCallback;
}
public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback) {
mOnScrollChangedCallback = onScrollChangedCallback;
}
/**
* Impliment in the activity/fragment/view that you want to listen to the webview
*/
public static interface OnScrollChangedCallback {
public void onScroll(int l, int t);
}
/**
* make this {@link WebView} vertically scroll only
*/
private void makeVerticalScrollOnly() {
// set onTouchListener for vertical scroll only
setOnTouchListener(this);
// hide horizontal scroll bar
setHorizontalScrollBarEnabled(false);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// multitouch is ignored
if (motionEvent.getPointerCount() > 1) {
return true;
}
// handle x coordinate on single touch events
switch (motionEvent.getAction()) {
// save the x coordinate on touch down
case MotionEvent.ACTION_DOWN:
touchDownX = motionEvent.getX();
break;
// reset the x coordinate on each other touch action, so it doesn't move
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
motionEvent.setLocation(touchDownX, motionEvent.getY());
break;
}
// let the super view handle the update
return false;
}
}