本文主要介绍如何解决ViewPager在ScrollView中滑动经常失效、无法正常滑动问题。
解决方法只需要在接近水平滚动时ScrollView不处理事件而交由其子View(即这里的ViewPager)处理即可,重写ScrollView的onInterceptTouchEvent函数,如下:
[java] view plaincopy
class="dp-j" start="1">
- package cc.newnews.view;
-
- import android.content.Context;
- import android.util.AttributeSet;
- import android.view.GestureDetector;
- import android.view.GestureDetector.SimpleOnGestureListener;
- import android.view.MotionEvent;
- import android.widget.ScrollView;
-
- 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) {
-
-
-
- return (Math.abs(distanceY) > Math.abs(distanceX));
- }
- }
- }
再将xml中的ScrollView改为<xxx.xxx.xxx.VerticalScrollView>即包名.重写的ScrollView的类名)即可。
本方法同样适用于ScrollView中ListView等其他View无法滚动。