ScrollView源码分析

本文详细分析了Android ScrollView的源码,重点探讨了onInterceptTouchEvent()和onTouchEvent(MotionEvent ev)两个方法。在onInterceptTouchEvent()中,ScrollView只在拖动时拦截事件,而onTouchEvent()包含了滚动逻辑的关键实现,包括对down、move和up事件的处理,以及如何与OverScroller、EdgeEffect和VelocityTracker等组件协同工作。通过这个分析,理解ScrollView的滚动细节至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

onInterceptTouchEvent()

先看返回值

onInterceptTouchEvent(){
       /*
        * The only time we want to intercept motion events is if we are in the
        * drag mode.
        */
        return mIsBeingDragged;
}
/**
 * True if the user is currently dragging this ScrollView around. This is
  * not the same as 'is being flinged', which can be checked by
  * mScroller.isFinished() (flinging begins when the user lifts his finger).
 */
    private boolean mIsBeingDragged = false;

可以看到ScrollView只在被拖动的时候拦截掉,来自己处理事件。
那么什么时候被拖动呢,一定是在上面的手势识别中处理的,显而易见move的时候一定是mIsBeingDragged = true的,up的时候一定是false的,可以在源码得到验证。有趣的是Down的时候。

case MotionEvent.ACTION_DOWN: {
                final int y = (int) ev.getY();
                if (!inChild((int) ev.getX(), (int) y)) {
                    mIsBeingDragged = false;
                    recycleVelocityTracker();
                    break;
                }

                /*
                 * Remember location of down touch.
                 * ACTION_DOWN always refers to pointer index 0.
                 */
                mLastMotionY = y;
                mActivePointerId = ev.getPointerId(0);

                initOrResetVelocityTracker();
                mVelocityTracker.addMovement(ev);
                /*
                 * If being flinged and user touches the screen, initiate drag;
                 * otherwise don't. mScroller.isFinished should be false when
                 * being flinged. We need to call computeScrollOffset() first so that
                 * isFinished() is correct.
                */
                mScroller.computeScrollOffset();
                mIsBeingDragged = !mScroller.isFinished();
                if (mIsBeingDra
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值