• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
mark_xiao
博客园    首页    新随笔    联系   管理    订阅  订阅

解决ScrollView嵌套viewpager滑动事件冲突问题

重写ScrollView

第一种方案能解决viewpager的滑动问题,但是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) {
            /**
             * if we're scrolling more closer to x direction, return false, let subview to process it
             */
            HBLog.i("VerticalScrollView", distanceY+"----"+distanceX);
            return (Math.abs(distanceY) > Math.abs(distanceX));
        }
    }

}

 

第二种方案能够解决上面的问题

public class VerticalScrollView extends ScrollView {

    private float xDistance, yDistance, xLast, yLast; 

    public VerticalScrollView(Context context) { 
        super(context); 
    } 

    public VerticalScrollView(Context context, AttributeSet attrs) { 
        super(context, attrs); 
    } 

    public VerticalScrollView(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); 
    }

}

 

posted @ 2016-03-03 12:14  mark_xiao  阅读(5105)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3