前段时间做项目碰到在ScrollView里添加ViewPager,但是发现ViewPager的左右滑动和ScrollView的滑动冲突了,解决这个问题的方法是重写ScrollView。
代码:
public class CustomScrollView extends ScrollView { private GestureDetector mGestureDetector;
View.OnTouchListener mGestureListener; public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
} public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
} public CustomScrollView(Context context) {
super(context);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
} @Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
} // Return false if we're scrolling in the x direction
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (Math.abs(distanceY) > Math.abs(distanceX)) {
return true;
}
return false;
}
} }