本文主要介绍如何解决ViewPager在ScrollView中滑动经常失效、无法正常滑动问题。
解决方法只需要在接近水平滚动时ScrollView不处理事件而交由其子View(即这里的ViewPager)处理即可,重写ScrollView的onInterceptTouchEvent函数,如下:
网上找到两种方法:
1.
public class VerticalScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public VerticalScrollView(Context context, AttributeSet attrs){
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
/**
* if we're scrolling more closer to x direction, return false, let subview to process it
*/
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
2.
public class MyScrollView extends ScrollView {
private float xDistance, yDistance, xLast, yLast;
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context,AttributeSet attrs){
super(context, attrs);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDistance = yDistance = 0f;
xLast = ev.getX();
yLast = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
xDistance += Math.abs(curX - xLast);
yDistance += Math.abs(curY - yLast);
xLast = curX;
yLast = curY;
if (xDistance > yDistance) {
return false;
}
}
return super.onInterceptTouchEvent(ev);
}
}