在上一章咱们介绍了Recyclerview在没有任何交互时是怎么布局的:Recyclerview源码剖析:一、静态时怎么布局,现在RV现已初始化好了,那当咱们进行滑动交互时代码又是怎么履行的呢?

RV优秀就优秀在他是动态布局的,与ScrollView不同在于:ScrollView是初始化时将一切child都inflateaddRV是只inflate屏幕展现得下的child.

假如咱们有100个child:

  • ScrollView便会在初始化时就inflateadd100个child,这样滑动的时分ScrollView不必履行过多的逻辑.
  • RV由于只会inflate部分child,所以当滑动的时分就会涉及动态inflateaddremove等逻辑.

RV再强大,他终究仍是View,那他也逃离不了android接触事件传递的限制,所以假如RV想要响应滑动事件,那一切的开端必定在onTouchEvent()中.

一切的开端

RV.onTouchEvent()

public boolean onTouchEvent(MotionEvent e) {
    if (mLayoutSuppressed || mIgnoreMotionEventTillDown) {
        return false;
    }
    if (dispatchToOnItemTouchListeners(e)) {
        cancelScroll();
        return true;
    }
    if (mLayout == null) {
        return false;
    }
    //判别滑动方向,这儿咱们挑选以笔直方向滑动为例
    final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
    final boolean canScrollVertically = mLayout.canScrollVertically();
    //这个便是创建一个 速度跟踪器
    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    boolean eventAddedToVelocityTracker = false;
    final int action = e.getActionMasked();
    final int actionIndex = e.getActionIndex();
    if (action == MotionEvent.ACTION_DOWN) {
        mNestedOffsets[0] = mNestedOffsets[1] = 0;
    }
    final MotionEvent vtev = MotionEvent.obtain(e);
    vtev.offsetLocation(mNestedOffsets[0], mNestedOffsets[1]);
    switch (action) {
        //DOWN 事件首要和嵌套滑动相关,所以这儿能够越过
        case MotionEvent.ACTION_DOWN: {
            mScrollPointerId = e.getPointerId(0);
            mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
            mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
            int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
            if (canScrollHorizontally) {
                nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
            }
            if (canScrollVertically) {
                nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
            }
            startNestedScroll(nestedScrollAxis, TYPE_TOUCH);
        }
        break;
        case MotionEvent.ACTION_POINTER_DOWN: {
            mScrollPointerId = e.getPointerId(actionIndex);
            mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f);
            mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f);
        }
        break;
        case MotionEvent.ACTION_MOVE: {
            final int index = e.findPointerIndex(mScrollPointerId);
            if (index < 0) {
                Log.e(TAG, "Error processing scroll; pointer index for id "
                        + mScrollPointerId + " not found. Did any MotionEvents get skipped?");
                return false;
            }
            //这儿首要核算手指滑动间隔
            final int x = (int) (e.getX(index) + 0.5f);
            final int y = (int) (e.getY(index) + 0.5f);
            int dx = mLastTouchX - x;
            int dy = mLastTouchY - y;
            //mScrollState的默认值是SCROLL_STATE_IDLE,
            //从名字上能看出来跟滑动状况相关,现在还没开端滑动,所以是默认值
            //经过检查mScrollState一切赋值的地方都是在滑动的逻辑
            //所以这个if条件建立
            if (mScrollState != SCROLL_STATE_DRAGGING) {
                boolean startScroll = false;
                //咱们以笔直滑动间隔
                if (canScrollHorizontally) {
                    if (dx > 0) {
                        dx = Math.max(0, dx - mTouchSlop);
                    } else {
                        dx = Math.min(0, dx + mTouchSlop);
                    }
                    if (dx != 0) {
                        startScroll = true;
                    }
                }
                if (canScrollVertically) {
                    //这儿首要是过滤没有达到最小滑动间隔的滑动
                    if (dy > 0) {
                        dy = Math.max(0, dy - mTouchSlop);
                    } else {
                        dy = Math.min(0, dy + mTouchSlop);
                    }
                    //滑动间隔合格
                    if (dy != 0) {
                        startScroll = true;
                    }
                }
                //判别当时是否应该滑动
                if (startScroll) {
                    //把标志位设置为应该滑动的状况,下面紧接着会用到
                    setScrollState(SCROLL_STATE_DRAGGING);
                }
            }
            //上面现已把mScrollState设置为SCROLL_STATE_DRAGGING
            //判别条件建立
            if (mScrollState == SCROLL_STATE_DRAGGING) {
                mReusableIntPair[0] = 0;
                mReusableIntPair[1] = 0;
                dx -= releaseHorizontalGlow(dx, e.getY());
                dy -= releaseVerticalGlow(dy, e.getX());
                //这儿和嵌套滑动相关,能够越过
                if (dispatchNestedPreScroll(
                        canScrollHorizontally ? dx : 0,
                        canScrollVertically ? dy : 0,
                        mReusableIntPair, mScrollOffset, TYPE_TOUCH
                )) {
                    dx -= mReusableIntPair[0];
                    dy -= mReusableIntPair[1];
                    // Updated the nested offsets
                    mNestedOffsets[0] += mScrollOffset[0];
                    mNestedOffsets[1] += mScrollOffset[1];
                    // Scroll has initiated, prevent parents from intercepting
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                mLastTouchX = x - mScrollOffset[0];
                mLastTouchY = y - mScrollOffset[1];
                //① 这儿是要点了
                if (scrollByInternal(
                        canScrollHorizontally ? dx : 0,
                        canScrollVertically ? dy : 0,
                        e, TYPE_TOUCH)) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                if (mGapWorker != null && (dx != 0 || dy != 0)) {
                    mGapWorker.postFromTraversal(this, dx, dy);
                }
            }
        }
        break;
        ...
        ...
    }
    if (!eventAddedToVelocityTracker) {
        mVelocityTracker.addMovement(vtev);
    }
    vtev.recycle();
    return true;
}

RV.scrollByInternal()

boolean scrollByInternal(int x, int y, MotionEvent ev, int type) {
    int unconsumedX = 0;
    int unconsumedY = 0;
    int consumedX = 0;
    int consumedY = 0;
    //这个函数首要是为了处理当在滑动的时分,adapter数据更新的状况
    //滑动的时分默认数据是不变的,可是adapter实际修改了数据,就会有crash
    consumePendingUpdateOperations();
    if (mAdapter != null) {
        mReusableIntPair[0] = 0;
        mReusableIntPair[1] = 0;
        //① 这儿又是要点了,滑动时的layout逻辑都在这儿
        scrollStep(x, y, mReusableIntPair);
        consumedX = mReusableIntPair[0];
        consumedY = mReusableIntPair[1];
        unconsumedX = x - consumedX;
        unconsumedY = y - consumedY;
    }
    //后边都是和滑动嵌套相关的逻辑,能够直接越过
    if (!mItemDecorations.isEmpty()) {
        invalidate();
    }
    mReusableIntPair[0] = 0;
    mReusableIntPair[1] = 0;
    dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, mScrollOffset,
            type, mReusableIntPair);
    unconsumedX -= mReusableIntPair[0];
    unconsumedY -= mReusableIntPair[1];
    boolean consumedNestedScroll = mReusableIntPair[0] != 0 || mReusableIntPair[1] != 0;
    // Update the last touch co-ords, taking any scroll offset into account
    mLastTouchX -= mScrollOffset[0];
    mLastTouchY -= mScrollOffset[1];
    mNestedOffsets[0] += mScrollOffset[0];
    mNestedOffsets[1] += mScrollOffset[1];
    if (getOverScrollMode() != View.OVER_SCROLL_NEVER) {
        if (ev != null && !MotionEventCompat.isFromSource(ev, InputDevice.SOURCE_MOUSE)) {
            pullGlows(ev.getX(), unconsumedX, ev.getY(), unconsumedY);
            // For rotary encoders, we release stretch EdgeEffects after they are pulled, to
            // avoid the effects being stuck pulled.
            if (Build.VERSION.SDK_INT >= 31
                    && MotionEventCompat.isFromSource(ev, InputDevice.SOURCE_ROTARY_ENCODER)) {
                releaseGlows();
            }
        }
        considerReleasingGlowsOnScroll(x, y);
    }
    if (consumedX != 0 || consumedY != 0) {
        dispatchOnScrolled(consumedX, consumedY);
    }
    if (!awakenScrollBars()) {
        invalidate();
    }
    return consumedNestedScroll || consumedX != 0 || consumedY != 0;
}

其实这儿面大部分逻辑都是处理嵌套滑动的,有layout相关的逻辑都在scrollStep()

LLM.scrollStep()

void scrollStep(int dx, int dy, @Nullable int[] consumed) {
    startInterceptRequestLayout();
    onEnterLayoutOrScroll();
    TraceCompat.beginSection(TRACE_SCROLL_TAG);
    fillRemainingScrollValues(mState);
    int consumedX = 0;
    int consumedY = 0;
    //这儿便是依据滑动方向进行滑动处理
    if (dx != 0) {
        consumedX = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
    }
    if (dy != 0) {
        consumedY = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
    }
    TraceCompat.endSection();
    repositionShadowingViews();
    onExitLayoutOrScroll();
    stopInterceptRequestLayout(false);
    if (consumed != null) {
        consumed[0] = consumedX;
        consumed[1] = consumedY;
    }
}

scrollStep()首要处理两件事,将滑动委托给LayoutManager和其他….

LLM.scrollVerticallyBy

public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler,
        RecyclerView.State state) {
    if (mOrientation == HORIZONTAL) {
        return 0;
    }
    //交给scrollBy()处理
    return scrollBy(dy, recycler, state);
}
int scrollBy(int delta, RecyclerView.Recycler recycler, RecyclerView.State state) {
    if (getChildCount() == 0 || delta == 0) {
        return 0;
    }
    ensureLayoutState();
    mLayoutState.mRecycle = true;
    //detail > 0 代表往上滑或许往左滑
    final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
    final int absDelta = Math.abs(delta);
    //经过滑动方历来更新layoutState中的各种参数
    updateLayoutState(layoutDirection, absDelta, true, state);
    //开端填充child
    final int consumed = mLayoutState.mScrollingOffset
            + fill(recycler, mLayoutState, state, false);
    if (consumed < 0) {
        if (DEBUG) {
            Log.d(TAG, "Don't have any more elements to scroll");
        }
        return 0;
    }
    final int scrolled = absDelta > consumed ? layoutDirection * consumed : delta;
    mOrientationHelper.offsetChildren(-scrolled);
    if (DEBUG) {
        Log.d(TAG, "scroll req: " + delta + " scrolled: " + scrolled);
    }
    mLayoutState.mLastScrollDelta = scrolled;
    return scrolled;
}

这儿的要点逻辑又进入到fill()这儿的fill()和静态布局时的逻辑差别不大,不同的是这儿规划Viewholder的收回,这儿的收回逻辑都在recycleByLayoutState()

LLM.fill()

int fill(RecyclerView.Recycler recycler, LayoutState layoutState,
        RecyclerView.State state, boolean stopOnFocusable) {
    // max offset we should set is mFastScroll + available
    final int start = layoutState.mAvailable;
    //①这儿的逻辑便是先判别哪些child会被划出屏幕,然后把他们进行收回
    if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) {
        // TODO ugly bug fix. should not happen
        if (layoutState.mAvailable < 0) {
            layoutState.mScrollingOffset += layoutState.mAvailable;
        }
        recycleByLayoutState(recycler, layoutState);
    }
    //核算总共有多少空间能够用来摆放child
    int remainingSpace = layoutState.mAvailable + layoutState.mExtraFillSpace;
    //一个用来保存每次布局一个child的结果类,比如一个child消费了多少空间
    //是否应该真实的核算这个child消费的空间(预布局的时分有些child尽管消费了空间,
    // 可是不应该不参加真实的空间剩余空间的核算)
    LayoutChunkResult layoutChunkResult = mLayoutChunkResult;
    //只要还有空间和item就进行布局layoutchunk
    while ((layoutState.mInfinite || remainingSpace > 0) && layoutState.hasMore(state)) {
        //重置上一次布局child的结果
        layoutChunkResult.resetInternal();
        if (RecyclerView.VERBOSE_TRACING) {
            TraceCompat.beginSection("LLM LayoutChunk");
        }
        //这儿是真实layout child的逻辑
        layoutChunk(recycler, state, layoutState, layoutChunkResult);
        if (RecyclerView.VERBOSE_TRACING) {
            TraceCompat.endSection();
        }
        if (layoutChunkResult.mFinished) {
            break;
        }
        //layoutState.mLayoutDirection的值是 1或许-1 所以这儿是 乘法
        //假如是从顶部往底部填充,当时填充的是第三个child 且每个高度是10dp,那么layoutState.mOffset的值
        //便是上次填充时的偏移量 + 这次填充child的高度
        //假如是从底部往顶部填充,那便是次填充时的偏移量 - 这次填充child的高度
        layoutState.mOffset += layoutChunkResult.mConsumed * layoutState.mLayoutDirection;
        /**
         * Consume the available space if:
         * * layoutChunk did not request to be ignored
         * * OR we are laying out scrap children
         * * OR we are not doing pre-layout
         */
        //判别是否要真实的消费当时child参加布局所消费的高度
        //从判别条件中能够看到预布局和这个有关,不过预布局等后边几章会具体说的
        //这儿便是同步现在还剩多少空间能够用来布局
        if (!layoutChunkResult.mIgnoreConsumed || layoutState.mScrapList != null
                || !state.isPreLayout()) {
            layoutState.mAvailable -= layoutChunkResult.mConsumed;
            // we keep a separate remaining space because mAvailable is important for recycling
            remainingSpace -= layoutChunkResult.mConsumed;
        }
        //在这个判别内履行滑出去的child进行收回
        if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) {
            layoutState.mScrollingOffset += layoutChunkResult.mConsumed;
            if (layoutState.mAvailable < 0) {
                layoutState.mScrollingOffset += layoutState.mAvailable;
            }
            //履行收回相关逻辑
            recycleByLayoutState(recycler, layoutState);
        }
        if (stopOnFocusable && layoutChunkResult.mFocusable) {
            break;
        }
    }
    if (DEBUG) {
        validateChildOrder();
    }
    return start - layoutState.mAvailable;
}

这儿的逻辑简直与Recyclerview源码剖析:一、静态时怎么布局一致,可是他在履行逻辑的开端进行了收回逻辑,并且在每次布局完一个child也会再次判别哪些child需要收回.

LLM.recycleByLayoutState()

private void recycleByLayoutState(RecyclerView.Recycler recycler, LayoutState layoutState) {
    if (!layoutState.mRecycle || layoutState.mInfinite) {
        return;
    }
    int scrollingOffset = layoutState.mScrollingOffset;
    int noRecycleSpace = layoutState.mNoRecycleSpace;
    //这儿咱们仍是以笔直布局手指向上滑动场景为例
    //因为手指向上滑动,就需要在底部填充child,所以layoutState.mLayoutDirection != LayoutState.LAYOUT_START
    //就会走到else逻辑中
    if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
        recycleViewsFromEnd(recycler, scrollingOffset, noRecycleSpace);
    } else {
        //①
        recycleViewsFromStart(recycler, scrollingOffset, noRecycleSpace);
    }
}
private void recycleViewsFromStart(RecyclerView.Recycler recycler, int scrollingOffset,
        int noRecycleSpace) {
    if (scrollingOffset < 0) {
        if (DEBUG) {
            Log.d(TAG, "Called recycle from start with a negative value. This might happen"
                    + " during layout changes but may be sign of a bug");
        }
        return;
    }
    // ignore padding, ViewGroup may not clip children.
    //举个栗子:屏幕高度100dp,每个child高度为15dp,此时屏幕会显现
    //7个child,可是第7个child没有全部显现,底部还有5dp的内容在屏幕
    //下方,这时分scrollingOffset=5dp
    final int limit = scrollingOffset - noRecycleSpace;
    final int childCount = getChildCount();
    if (mShouldReverseLayout) {
        for (int i = childCount - 1; i >= 0; i--) {
            View child = getChildAt(i);
            if (mOrientationHelper.getDecoratedEnd(child) > limit
                    || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) {
                // stop here
                recycleChildren(recycler, childCount - 1, i);
                return;
            }
        }
    } else {
        //从顶部第一个child开端找,找到第一个child的bottom>scrollingOffset(5dp)的child
        //那么这个child之前的一切child在这次滑动中都会划出屏幕
        //所以要把他们都收回掉
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            if (mOrientationHelper.getDecoratedEnd(child) > limit
                    || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) {
                // stop here
                recycleChildren(recycler, 0, i);
                return;
            }
        }
    }
}

总结一下便是:RV在滑动的时分会把滑动的间隔交给LayoutManager处理和消费,LayoutManager会遍历当时一切的child并依据他们的位置加上这次滑动间隔,判别哪些child会划出屏幕,然后就把他们给收回掉.