> 文章列表 > 深入理解 RecyclerView 的绘制流程和滑动原理

深入理解 RecyclerView 的绘制流程和滑动原理

深入理解 RecyclerView 的绘制流程和滑动原理

一、绘制流程

RecyclerView支持各种各样的布局效果,其核心关键在于RecyclerView.LayoutManager中,使用时我们是需要setLayoutManager()设置布局管理器的。RecyclerView已经将一部分功能抽离出来,在布局管理器中另外处理,也方便开发者自行拓展。LayoutManager****就是负责RecyclerView的测量和布局以及itemView的回收和复用。今天这里主要结合LinearLayoutManager来分析RecyclerView的绘制流程。

RecyclerView提供了三中布局管理器:

  • LinearLayoutManager      以列表的方式展示item,有水平方向RecyclerView.HORIZONTAL和垂直方向RecyclerView.VERTICAL;
  • GridLayoutManager       以网格的方式展示item,有水平方向和垂直方向;
  • StaggeredGridLayoutManager   以瀑布流的方式展示item,有水平方向和垂直方向。

这里以LinearLayoutManager为例来分析RecyclerView的绘制流程。

温馨提示:本文源码基于androidx.recyclerview:recyclerview:1.2.0-alpha01

1.1、RecyclerView的绘制三个步骤

RecyclerView设置布局管理器,这一步是必要的,用什么样的LayoutManager来绘制RecyclerView,不然RecyclerView也不知道怎么绘制。

 recyclerView.setLayoutManager(manager);

从设置布局管理器方法入手,setLayoutManager()设置布局管理器给RecyclerView使用:

   public void setLayoutManager(@Nullable LayoutManager layout) {if (layout == mLayout) {//和之前的管理器一样则直接returnreturn;}stopScroll();//停止滚动if (mLayout != null) {//每次设置layoutManager都重新设置recyclerView的初始参数,动画回收view等if (mItemAnimator != null) {mItemAnimator.endAnimations();//结束动画}mLayout.removeAndRecycleAllViews(mRecycler);//移除回收所有itemViewmLayout.removeAndRecycleScrapInt(mRecycler);//移除回收所有已经废弃的itemViewmRecycler.clear();//清除所有缓存mLayout.setRecyclerView(null);//重置RecyclerViewmLayout = null;} else {mRecycler.clear();}·······mLayout.setRecyclerView(this);//LayoutManager与RecyclerView关联mRecycler.updateViewCacheSize();//更新缓存大小requestLayout();//请求重绘}

这里首先做了重置回收工作,然后LayoutManager与RecyclerView关联起来,最后请求重绘。这里调用了请求重绘requestLayout()方法,那么说明每次设置layoutManager都会执行View树的绘制,那么就会重走RecyclerView的onMeasure()onLayout()onDraw()绘制三部曲。

    public void requestLayout() {if (mRecyclerView != null) {mRecyclerView.requestLayout();//请求重绘}}

1. onMeasure()

我们来看看RecyclerView的onMeasure()方法:

    @Overrideprotected void onMeasure(int widthSpec, int heightSpec) {if (mLayout == null) {//如果mLayout为空则采用默认测量,然后结束defaultOnMeasure(widthSpec, heightSpec);return;}if (mLayout.mAutoMeasure) {//如果为自动测量,默认为truefinal int widthMode = MeasureSpec.getMode(widthSpec);final int heightMode = MeasureSpec.getMode(heightSpec);mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);//测量RecyclerView的宽高//当前RecyclerView的宽高是否为精确值final boolean measureSpecModeIsExactly =widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY;if (measureSpecModeIsExactly || mAdapter == null) {//如果RecyclerView的宽高为精确值或者mAdapter为空,则结束return;}//RecyclerView的宽高为wrap_content时,即measureSpecModeIsExactly = false则进行测量//因为RecyclerView的宽高为wrap_content时,需要先测量itemView的宽高才能知道RecyclerView的宽高if (mState.mLayoutStep == State.STEP_START) {//还没测量过dispatchLayoutStep1();//1.适配器更新、动画运行、保存当前视图的信息、运行预测布局}dispatchLayoutStep2();//2.最终实际的布局视图,如果有必要会多次运行//根据itemView得到RecyclerView的宽高mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);}}

onMeasure()主要是RecyclerView宽高测量工作,主要有两种情况:

  • (1)当RecyclerView的宽高为match_parent或者精确值时,即measureSpecModeIsExactly = true,此时只需要测量自身的宽高就知道RecyclerView的宽高,测量方法结束;
  • (2)当RecyclerView的宽高为wrap_content时,即measureSpecModeIsExactly = false,会往下执行dispatchLayoutStep1()dispatchLayoutStep2(),就是遍历测量ItemView的大小从而确定RecyclerView的宽高,这种情况真正的测量操作都是在dispatchLayoutStep2()中完成。

dispatchLayoutStep1()dispatchLayoutStep2()下面会讲解到。

2. onLayout()

onLayout()方法中, 直接调用dispatchLayout()方法布局:

   @Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {TraceCompat.beginSection(TRACE_ON_LAYOUT_TAG);dispatchLayout(); //直接调用dispatchLayout()方法布局TraceCompat.endSection();mFirstLayoutComplete = true;}

dispatchLayout()layoutChildren()的包装器,它处理由布局引起的动态变化:

  void dispatchLayout() {······mState.mIsMeasuring = false;//设置RecyclerView布局完成状态,前面已经设置预布局完成了。if (mState.mLayoutStep == State.STEP_START) {//如果没在OnMeasure阶段提前测量子ItemViewdispatchLayoutStep1();//布局第一步:适配器更新、动画运行、保存当前视图的信息、运行预测布局mLayout.setExactMeasureSpecsFrom(this);dispatchLayoutStep2();} else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth()|| mLayout.getHeight() != getHeight()) {//前两步完成测量,但是因为大小改变不得不再次运行下面的代码mLayout.setExactMeasureSpecsFrom(this);dispatchLayoutStep2();//布局第二步:最终实际的布局视图,如果有必要会多次运行} else {mLayout.setExactMeasureSpecsFrom(this);}dispatchLayoutStep3();//布局第三步:最后一步的布局,保存视图动画、触发动画和不必要的清理。}

可以看到dispatchLayout()onMeasure()阶段中一样选择性地进行测量布局的三个步骤:

  • 1、如果没在onMeasure阶段提前测量子ItemView,即RecyclerView宽高为match_parent或者精确值时,调用dispatchLayoutStep1()dispatchLayoutStep2()测量itemView宽高;
  • 2、如果在onMeasure阶段提前测量子ItemView,但是子视图发生了改变或者期望宽高和实际宽高不一致,则会调用dispatchLayoutStep2()重新测量;
  • 3、最后都会执行dispatchLayoutStep3()方法。

(1)我们来看看dispatchLayoutStep1、2、3分发布局的三个步骤:dispatchLayoutStep1()主要是进行预布局,适配器更新、动画运行、保存当前视图的信息等工作;

  private void dispatchLayoutStep1() {mState.assertLayoutStep(State.STEP_START);fillRemainingScrollValues(mState);mState.mIsMeasuring = false;startInterceptRequestLayout();//拦截布局请求mViewInfoStore.clear();//itemView信息清除onEnterLayoutOrScroll();//测量和分派布局时,更新适配器和计算那种类型要运行的动画processAdapterUpdatesAndSetAnimationFlags();saveFocusInfo();//保存焦点信息mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;mItemsAddedOrRemoved = mItemsChanged = false;mState.mInPreLayout = mState.mRunPredictiveAnimations;mState.mItemCount = mAdapter.getItemCount();findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);//找到可绘制itemView最小最大positionif (mState.mRunSimpleAnimations) {//获得界面上可以显示的个数int count = mChildHelper.getChildCount();for (int i = 0; i < count; ++i) {final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));//动画信息final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation(mState, holder,ItemAnimator.buildAdapterChangeFlagsForAnimations(holder),holder.getUnmodifiedPayloads());//保存holder和动画信息到预布局中mViewInfoStore.addToPreLayout(holder, animationInfo);}}//运行与布局,将会使用旧的item的position,布局管理器布局所有if (mState.mRunPredictiveAnimations) {//保存旧的管理器可以运行的逻辑saveOldPositions();final boolean didStructureChange = mState.mStructureChanged;mState.mStructureChanged = false;//布局itemViewmLayout.onLayoutChildren(mRecycler, mState);mState.mStructureChanged = didStructureChange;}stopInterceptRequestLayout(false);//回复绘制锁定mState.mLayoutStep = State.STEP_LAYOUT;}

(2)dispatchLayoutStep2()表示对最终状态的视图进行实际布局:

  private void dispatchLayoutStep2() {startInterceptRequestLayout();//拦截请求布局onEnterLayoutOrScroll();//设置布局状态和动画状态mState.assertLayoutStep(State.STEP_LAYOUT | State.STEP_ANIMATIONS);mAdapterHelper.consumeUpdatesInOnePass();mState.mItemCount = mAdapter.getItemCount();mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;//预布局完成,开始布局itemViewmState.mInPreLayout = false;mLayout.onLayoutChildren(mRecycler, mState);······stopInterceptRequestLayout(false);//停止拦截布局请求}

(3)dispatchLayoutStep3()是布局的最后一步,保存view的动画信息,执行动画,和一些必要的清理工作:

   private void dispatchLayoutStep3() {mState.assertLayoutStep(State.STEP_ANIMATIONS);startInterceptRequestLayout();//开始拦截布局请求mState.mLayoutStep = State.STEP_START;//布局开始状态if (mState.mRunSimpleAnimations) {//步骤3:找出事情现在的位置,并处理更改动画。//反向遍历列表,因为我们可能会在循环中调用animateChange,这可能会删除目标视图持有者。for (int i = mChildHelper.getChildCount() - 1; i >= 0; i--) {ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));final ItemHolderInfo animationInfo = mItemAnimator.recordPostLayoutInformation(mState, holder);ViewHolder oldChangeViewHolder = mViewInfoStore.getFromOldChangeHolders(key);//运行一个变更动画。如果一个项目被更改,但是更新后的版本正在消失,则会产生冲突的情况。//由于标记为正在消失的视图可能会超出界限,所以我们运行一个change动画。两个视图都将在动画完成后自动清除。//另一方面,如果是相同的视图持有者实例,我们将运行一个正在消失的动画,因为我们不会重新绑定更新的VH,除非它是由布局管理器强制执行的。//运行消失动画而不是改变mViewInfoStore.addToPostLayout(holder, animationInfo);final ItemHolderInfo preInfo = mViewInfoStore.popFromPreLayout(oldChangeViewHolder);//我们添加和删除,这样任何的布置信息都是合并的mViewInfoStore.addToPostLayout(holder, animationInfo);ItemHolderInfo postInfo = mViewInfoStore.popFromPostLayout(holder);mViewInfoStore.addToPostLayout(holder, animationInfo);}//处理视图信息列表和触发动画mViewInfoStore.process(mViewInfoProcessCallback);}//回收废弃的视图mLayout.removeAndRecycleScrapInt(mRecycler);//重置状态mState.mPreviousLayoutItemCount = mState.mItemCount;mDataSetHasChangedAfterLayout = false;//清除mChangedScrap中的数据mRecycler.mChangedScrap.clear();mRecycler.updateViewCacheSize();//更新缓存大小mLayout.onLayoutCompleted(mState);//布局完成状态onExitLayoutOrScroll();stopInterceptRequestLayout(false);//停止拦截布局请求mViewInfoStore.clear();//itemView信息清除recoverFocusFromState();//回复焦点resetFocusInfo();//重置焦点信息}

归纳分发布局的三个步骤:

  • dispatchLayoutStep1():  表示进行预布局,适配器更新、动画运行、保存当前视图的信息等工作;
  • dispatchLayoutStep2():  表示对最终状态的视图进行实际布局,有必要时会多次执行;
  • dispatchLayoutStep3():  表示布局最后一步,保存和触发有关动画的信息,相关清理等工作。

3. onDraw()

来到最后一步的绘制onDraw()方法中,如果不需要一些特殊的效果,在TextView、ImageView控件中已经绘制完了。

    @Overridepublic void onDraw(Canvas c) {super.onDraw(c);//所有itemView先绘制//分别绘制ItemDecorationfinal int count = mItemDecorations.size();for (int i = 0; i < count; i++) {mItemDecorations.get(i).onDraw(c, this, mState);}}

4. 绘制流程总结:

1、RecyclerView的itemView可能会被测量多次,如果RecyclerView的宽高是固定值或者match_parent,那么在onMeasure()阶段是不会提前测量ItemView布局,如果RecyclerView的宽高是wrap_content,由于还没有知道RecyclerView的实际宽高,那么会提前在onMeasure()阶段遍历测量itemView布局确定内容显示区域的宽高值来确定RecyclerView的实际宽高;

2、dispatchLayoutStep1()dispatchLayoutStep2()dispatchLayoutStep3()这三个方法一定会执行,在RecyclerView的实际宽高不确定时,会提前多次执行dispatchLayoutStep1()dispatchLayoutStep2()方法,最后在onLayout()阶段执行 dispatchLayoutStep3(),如果有itemView发生改变会再次执行dispatchLayoutStep2()

3、正在的测量和布局itemView实际在dispatchLayoutStep2()方法中。

RecyclerView的绘制三个步骤流程图: 深入理解 RecyclerView 的绘制流程和滑动原理

2.2、LinearLayoutManager填充、测量、布局过程

RecyclerView的绘制经过measure、layout、draw三个步骤,但是itemView的真正布局时委托给各个的LayoutManager中处理,上面LinearLayoutManager可以知道dispatchLayoutStep2()是实际布局视图步骤,通过LayoutManager调用onLayoutChildren()方法进行布局itemView,它是绘制itemView的核心方法,表示从给定的适配器中列出所有相关的子视图。

1. onLayoutChildren()布局itemView

    @Overridepublic void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {// 1) 检查子类和其他变量找到描点坐标和描点位置// 2) 从开始填补,从底部堆积// 3) 从底部填补,从顶部堆积// 4) 从底部堆积来满足需求// 创建布局状态if (mPendingSavedState != null || mPendingScrollPosition != RecyclerView.NO_POSITION) {if (state.getItemCount() == 0) {removeAndRecycleAllViews(recycler);//移除所有子Viewreturn;}}ensureLayoutState();mLayoutState.mRecycle = false;//禁止回收//颠倒绘制布局resolveShouldLayoutReverse();final View focused = getFocusedChild();//获取目前持有焦点的childif (!mAnchorInfo.mValid || mPendingScrollPosition != RecyclerView.NO_POSITION|| mPendingSavedState != null) {mAnchorInfo.reset();//重置锚点信息mAnchorInfo.mLayoutFromEnd = mShouldReverseLayout ^ mStackFromEnd;//1. 计算更新描点位置和坐标updateAnchorInfoForLayout(recycler, state, mAnchorInfo);mAnchorInfo.mValid = true;}·······//计算第一布局的方向int startOffset;int endOffset;final int firstLayoutDirection;onAnchorReady(recycler, state, mAnchorInfo, firstLayoutDirection);detachAndScrapAttachedViews(recycler);//暂时分离已经附加的view,即将所有child detach并通过Scrap回收mLayoutState.mInfinite = resolveIsInfinite();mLayoutState.mIsPreLayout = state.isPreLayout();mLayoutState.mNoRecycleSpace = 0;//2.开始填充,从底部开始堆叠;if (mAnchorInfo.mLayoutFromEnd) {//描点位置从start位置开始填充ItemView布局updateLayoutStateToFillStart(mAnchorInfo);fill(recycler, mLayoutState, state, false);//填充所有itemView//描点位置从end位置开始填充ItemView布局updateLayoutStateToFillEnd(mAnchorInfo);fill(recycler, mLayoutState, state, false);//填充所有itemViewendOffset = mLayoutState.mOffset;}else { //3.向底填充,从上往下堆放;//描点位置从end位置开始填充ItemView布局updateLayoutStateToFillEnd(mAnchorInfo);fill(recycler, mLayoutState, state, false);//描点位置从start位置开始填充ItemView布局updateLayoutStateToFillStart(mAnchorInfo);fill(recycler, mLayoutState, state, false);startOffset = mLayoutState.mOffset;}//4.计算滚动偏移量,如果有必要会在调用fill方法去填充新的ItemViewlayoutForPredictiveAnimations(recycler, state, startOffset, endOffset);}

首先是状态判断和一些准备工作,对描点信息选择和更新detachAndScrapAttachedViews(recycler)暂时将已经附加的view分离,缓存Scrap中,下次重新填充时直接拿出来复用。然后计算是从哪个方向开始布局。布局算法如下:

  • 1.通过检查子元素和其他变量,找到一个锚点坐标和一个锚点项的位置;
  • 2.开始填充,从底部开始堆叠;
  • 3.向底填充,从上往下堆放;
  • 4.滚动以满足要求,如堆栈从底部。

2. fill()开始填充itemView

填充布局交给了fill()方法,表示填充由layoutState定义的给定布局。为什么要fill两次呢?我们来看看fill()方法:

  //填充方法,返回的是填充itemView的像素,方便后续滚动时使用int fill(RecyclerView.Recycler recycler, LayoutState layoutState,RecyclerView.State state, boolean stopOnFocusable) {recycleByLayoutState(recycler, layoutState);//回收滑出屏幕的viewint remainingSpace = layoutState.mAvailable + layoutState.mExtraFillSpace;LayoutChunkResult layoutChunkResult = mLayoutChunkResult;//核心  == while()循环 ==while ((layoutState.mInfinite || remainingSpace > 0) && layoutState.hasMore(state)) {//一直循环,知道没有数据layoutChunkResult.resetInternal();//填充itemView的核心方法layoutChunk(recycler, state, layoutState, layoutChunkResult);······if (layoutChunkResult.mFinished) {//布局结束,退出循环break;}layoutState.mOffset += layoutChunkResult.mConsumed * layoutState.mLayoutDirection;//根据添加的child高度偏移计算   }······return start - layoutState.mAvailable;//返回这次填充的区域大小}

fill()核心就是一个while()循环,循环执行layoutChunk()填充一个itemView到屏幕,同时返回这次填充的区域大小。首先根据屏幕还有多少剩余空间remainingSpace,根据这个数值减去子View所占的空间大小,小于0时布局子View结束,如果当前所有子View还没有超过remainingSpace时,调用layoutChunk()安排View的位置。

3. layoutChunk()对itemView创建、填充、测量、布局

layoutChunk()作为最终填充布局itemView的方法,对itemView创建、填充、测量、布局,主要有以下几个步骤:

  • 1.layoutState.next(recycler)从缓存中获取itemView,如果没有则创建itemView;
  • 2.根据实际情况来添加itemView到RecyclerView中,最终调用的还是ViewGroup的addView()方法;
  • 3.measureChildWithMargins()测量itemView大小包括父视图的填充、项目装饰和子视图的边距;
  • 4.根据计算好的left, top, right, bottom通过layoutDecoratedWithMargins()使用坐标在RecyclerView中布局给定的itemView。
   void layoutChunk(RecyclerView.Recycler recycler, RecyclerView.State state,LayoutState layoutState, LayoutChunkResult result) {//1.从缓存中获取或者创建itemViewView view = layoutState.next(recycler);//获取当前postion需要展示的View······//2.根据实际情况来添加itemView到RecyclerView中,最终调用的还是ViewGroup的addView()方法if (layoutState.mScrapList == null) {if (mShouldReverseLayout == (layoutState.mLayoutDirection== LayoutState.LAYOUT_START)) {addView(view);} else {addView(view, 0);}} //3.测量子View大小包括父视图的填充、项目装饰和子视图的边距measureChildWithMargins(view, 0, 0);result.mConsumed = mOrientationHelper.getDecoratedMeasurement(view);//计算一个ItemView的left, top, right, bottom坐标值int left, top, right, bottom;······//4.使用坐标在RecyclerView中布局给定的itemView//计算正确的布局位置,减去margin,计算所有视图的边界框(包括margin和装饰)layoutDecoratedWithMargins(view, left, top, right, bottom);//调用child.layout进行布局}

通过layoutState.next()从缓存中获取itemView如果没有就创建一个新的itemView,然后addView()根据实际情况来添加itemView到RecyclerView中,最终调用的还是ViewGroup的addView()方法,接着通过 measureChildWithMargins()测量子View大小包括父视图的填充、项目装饰和子视图的边距;最后getDecoratedMeasuredWidth()通过计算好的left, top, right, bottom值在RecyclerView坐标中布局给定的itemView,注意这里的宽度是item+decoration的总宽度。

   View next(RecyclerView.Recycler recycler) {if (mScrapList != null) {return nextViewFromScrapList();}final View view = recycler.getViewForPosition(mCurrentPosition);mCurrentPosition += mItemDirection;return view;}

获取itemView,并且如果mScrapList 中有缓存的View 则使用缓存的view,如果没有mScrapList 就创建view,并添加到mScrapList 中。接下来getViewForPosition()方法主要是RecyclerView的缓存机制,后续的文章会讲解到。

4. LinearLayoutManager填充、测量、布局过程总结:

onLayoutChildren()表示从给定的适配器中列出所有相关的子视图,填充布局交给了fill()方法,填充由layoutState定义的给定布局,while()循环执行layoutChunk()填充一个itemView到屏幕,作为最终填充布局itemView的方法,layoutState.next(recycler)从缓存中获取或者创建itemView,通过addView()添加itemView到RecyclerView中,其实最终调用的还是ViewGroup的addView()方法,measureChildWithMargins()测量itemView大小包括父视图的填充、项目装饰和子视图的边距,最后layoutDecoratedWithMargins()根据计算好的left, top, right, bottom通过使用坐标在RecyclerView中布局给定的itemView。

流程图如下:

深入理解 RecyclerView 的绘制流程和滑动原理

二、滑动原理

RecyclerView作为一个列表控件,自带滑动功能,实际开发中经常用到,它的滑动原理也是我们需要掌握的,正所谓“知其然更要知其之所然”。RecyclerView的滑动事件处理依然是通过onTouchEvent()触控事件响应的,不同的是RecyclerView采用嵌套滑动机制,会把滑动事件通知给支持嵌套滑动的父View先做决定。本文在介绍普通滑动的过程中可能会涉及到嵌套滑动的知识(下篇文章会分析嵌套滑动),先来看看普通滑动的效果图:

深入理解 RecyclerView 的绘制流程和滑动原理

2.1、onTouchEvent()

RecyclerView的事件处理依然是通过onTouchEvent()触控事件响应的,这里补充一点onTouchEvent()的知识,熟悉的可以略过。

  • boolean onTouchEvent(MotionEvent event):  实现此方法来处理触摸屏运动事件,返回值true表示处理事件,false表示不处理事件;
  • MotionEvent.ACTION_DOWN:   手指按下,一个按下的手势已经开始,该动作包括初始的起始位置;
  • MotionEvent.ACTION_MOVE:   手指移动,在按下手势时(在down和up之间)发生了改变,该运动包含最近的点,以及自上次向下或移动事件以来的任何中间点;
  • MotionEvent.ACTION_UP:     手指离开,一个按下的手势已经完成,该动作包含一个最终的发布位置以及自上一个向下或移动事件以来的任何中间点;
  • MotionEvent.ACTION_CANCEL: 手势取消,当前手势已经终止,你不会得到更多的坐标点,可以将此视为up事件,但不执行任何你通常会执行的操作;
  • MotionEvent.ACTION_POINTER_DOWN:  多个手指按下,一个非主触摸点在下降;
  • MotionEvent.ACTION_POINTER_UP:    多个手指离开,一个非主触摸点上升;
  • MotionEvent.ACTION_OUTSIDE:     手指触碰超出了正常边界,移动发生在UI元素的正常范围之外。这并不是提供一个完整的手势,但只是提供了运动触摸的初始位置;注意,因为任何事件的位置都在视图层次结构的边界之外,所以默认情况它不会被分配给ViewGroup的任何子元素;
  • MotionEvent.ACTION_SCROLL:     非触摸滑动,运动事件包含相对的垂直/水平滚动偏移量,这个动作不是触摸事件。

先来看看RecyclerView的onTouchEvent()方法:

  	@Overridepublic boolean onTouchEvent(MotionEvent e) {//将滑动事件分派给OnItemTouchListener或为OnItemTouchListeners提供拦截机会,触摸事件被拦截处理则返回trueif (findInterceptingOnItemTouchListener(e)) {cancelScroll();return true;}//根据布局方向来决定滑动的方向final boolean canScrollHorizontally = mLayout.canScrollHorizontally();//能否支持水平方向滑动final boolean canScrollVertically = mLayout.canScrollVertically();//能否支持垂直方向滑动//获取一个新的VelocityTracker对象来观察滑动的速度if (mVelocityTracker == null) {mVelocityTracker = VelocityTracker.obtain();}mVelocityTracker.addMovement(e);//返回正在执行的操作,不包含触摸点索引信息。即事件类型,如MotionEvent.ACTION_DOWNfinal int action = e.getActionMasked();final int actionIndex = e.getActionIndex();//Action的索引//复制事件信息创建一个新的事件final MotionEvent vtev = MotionEvent.obtain(e);vtev.offsetLocation(mNestedOffsets[0], mNestedOffsets[1]);switch (action) {case MotionEvent.ACTION_DOWN: {//手指按下mScrollPointerId = e.getPointerId(0);//特定触摸点相关联的触摸点id,获取第一个触摸点的id//记录down事件的X、Y坐标mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);if (canScrollHorizontally) {nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;//指示沿水平轴滑动}if (canScrollVertically) {nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;//指示沿纵轴滑动}//开启一个新的嵌套滚动,如果找到一个协作的父View,并开始嵌套滑动startNestedScroll(nestedScrollAxis, TYPE_TOUCH);} break;case MotionEvent.ACTION_POINTER_DOWN: {//多个手指按下//更新mScrollPointerId,表示只会响应最近按下的手势事件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: {//手指移动//根据mScrollPointerId获取触摸点下标final int index = e.findPointerIndex(mScrollPointerId);//根据move事件产生的x,y来计算偏移量dx,dy 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;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);}}//被触摸移动状态,真正处理滑动的地方if (mScrollState == SCROLL_STATE_DRAGGING) {mReusableIntPair[0] = 0;//mReusableIntPair父view消耗的滑动距离mReusableIntPair[1] = 0;//mScrollOffset表示RecyclerView的滚动位置//将嵌套的预滑动操作的一个步骤分派给当前嵌套的滑动父View,如果为true表示父View优先处理滑动事件。//如果消耗,dx dx会分别减去父View消耗的那一部分距离if (dispatchNestedPreScroll(canScrollHorizontally ? dx : 0, canScrollVertically ? dy : 0,mReusableIntPair, mScrollOffset, TYPE_TOUCH)) {dx -= mReusableIntPair[0];//减去父View消耗的那一部分距离dx -= mReusableIntPair[1];//更新嵌套的偏移量mNestedOffsets[0] += mScrollOffset[0];mNestedOffsets[1] += mScrollOffset[1];//滑动已经开始,防止父View被拦截getParent().requestDisallowInterceptTouchEvent(true);}mLastTouchX = x - mScrollOffset[0];mLastTouchY = y - mScrollOffset[1];//最终实现的滑动效果if (scrollByInternal(canScrollHorizontally ? dx : 0, canScrollVertically ? dy : 0, e)) {getParent().requestDisallowInterceptTouchEvent(true);}//从缓存中预取一个ViewHolderif (mGapWorker != null && (dx != 0 || dy != 0)) {mGapWorker.postFromTraversal(this, dx, dy);}}} break;case MotionEvent.ACTION_POINTER_UP: {//多个手指离开//选择一个新的触摸点来处理结局,重新处理坐标onPointerUp(e);} break;case MotionEvent.ACTION_UP: {//手指离开,滑动事件结束mVelocityTracker.addMovement(vtev);eventAddedToVelocityTracker = true;//计算滑动速度mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);//最后一次 X/Y 轴的滑动速度final float xvel = canScrollHorizontally ? -mVelocityTracker.getXVelocity(mScrollPointerId) : 0;final float yvel = canScrollVertically ? -mVelocityTracker.getYVelocity(mScrollPointerId) : 0;//处理惯性滑动if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {setScrollState(SCROLL_STATE_IDLE);//设置滑动状态}resetScroll();//重置滑动} break;case MotionEvent.ACTION_CANCEL: {//手势取消,释放各种资源cancelScroll();//退出滑动} break;}if (!eventAddedToVelocityTracker) {mVelocityTracker.addMovement(vtev);}vtev.recycle();//回收滑动事件,方便重用,调用此方法你不能再接触事件return true;//返回true表示由RecyclerView来处理事件}

上面就是RecyclerView的onTouchEvent()方法,其中ACTION_DOWNACTION_MOVEACTION_UPACTION_CANCEL这几个事件是View的基本事件,ACTION_POINTER_DOWNACTION_POINTER_UP这个两个事件跟多指滑动有关。

这里主要做了三件事,

  • 一是将滑动事件分派给OnItemTouchListener或为OnItemTouchListeners提供拦截机会,被拦截处理则返回true,即消费掉事件;
  • 二是初始化手势坐标,滑动方向,事件信息等数据;
  • 三是OnItemTouchListener或OnItemTouchListeners不消费当前事件,那么走正常的事件分发流程。

这里面有很多细节,我们逐个事件来详细分析:

1. Down事件

    case MotionEvent.ACTION_DOWN:{//手指按下mScrollPointerId = e.getPointerId(0);//特定触摸点相关联的触摸点id,获取第一个触摸点的id//1.记录down事件的X、Y坐标mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);if (canScrollHorizontally) {nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;//指示沿水平轴滑动}if (canScrollVertically) {nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;//指示沿纵轴滑动}//2.开启一个新的嵌套滑动,如果找到一个协作的父View,并开始嵌套滚动startNestedScroll(nestedScrollAxis, TYPE_TOUCH);} break;

Down事件首先获取第一个触摸点id,一个Pointer就是一个触摸点,down是一系列事件的开始,这里主要做了两件事:

  • 1.记录down事件的X,Y坐标;
  • 2.调用startNestedScroll()启一个新的嵌套滑动,如果找到嵌套的父View则会启动嵌套滑动,即处理事件。

2. Move事件

   case MotionEvent.ACTION_MOVE:{//手指移动//根据mScrollPointerId获取触摸点下标final int index = e.findPointerIndex(mScrollPointerId);//1.根据move事件产生的x,y来计算偏移量dx,dy 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;if (mScrollState != SCROLL_STATE_DRAGGING) {//不是被触摸移动状态boolean startScroll = false;if (canScrollHorizontally) {//水平滑动的方向······}if (canScrollVertically) {//垂直滑动的方向······}//设置滑动状态,SCROLL_STATE_DRAGGING表示正在滑动中if (startScroll) setScrollState(SCROLL_STATE_DRAGGING);}//被触摸移动状态,真正处理滑动的地方if (mScrollState == SCROLL_STATE_DRAGGING) {mReusableIntPair[0] = 0;//mReusableIntPair父view消耗的滑动距离mReusableIntPair[1] = 0;//2.将嵌套的预滑动操作的一个步骤分派给当前嵌套的滚动父View,如果为true表示父View优先处理滑动事件。//如果消耗,dx dy会分别减去父View消耗的那一部分距离,mScrollOffset表示RecyclerView的滚动位置if (dispatchNestedPreScroll(canScrollHorizontally ? dx : 0, canScrollVertically ? dy : 0,mReusableIntPair, mScrollOffset, TYPE_TOUCH)) {dx -= mReusableIntPair[0];//减去父View消耗的那一部分距离dy -= mReusableIntPair[1];//更新嵌套的偏移量mNestedOffsets[0] += mScrollOffset[0];mNestedOffsets[1] += mScrollOffset[1];//开始滑动,防止父View被拦截getParent().requestDisallowInterceptTouchEvent(true);}mLastTouchX = x - mScrollOffset[0];mLastTouchY = y - mScrollOffset[1];//3.最终实现的滚动效果if (scrollByInternal(canScrollHorizontally ? dx : 0, canScrollVertically ? dy : 0, e)) {getParent().requestDisallowInterceptTouchEvent(true);}//4.从缓存中预取一个ViewHolderif (mGapWorker != null && (dx != 0 || dy != 0)) {mGapWorker.postFromTraversal(this, dx, dy);}}} break;

Move事件是处理滑动事件的核心,代码比较长,但是结构简单,主要分为如下几步:

  • 1.根据move事件产生的x、y计算偏移量dx,dy;
  • 2.dispatchNestedPreScroll()分派一个步骤询问父View是否需要先处理滑动事件,如果处理则dx,dy会分别减去父View消耗的那一部分距离;
  • 3.判断滑动方向,调用scrollByInternal()最终实现滚动效果;
  • 4.调用mGapWorker.postFromTraversal()从RecyclerView缓存中预取一个ViewHolder。

scrollByInternal()是最终实现滑动效果,后面会详细分析,GapWorker预取ViewHolder是通过添加Runnable到RecyclerView任务队列中,最终调用RecyclerView.Recycler的tryGetViewHolderForPositionByDeadline()获取ViewHolder,它是整个RecyclerView回收复用缓存机制的核心方法。这里就不详细分析了,《RecyclerView的回收复用缓存机制详解》希望能给你提供帮助。

3. Up事件

   case MotionEvent.ACTION_UP: {//手指离开,滑动事件结束mVelocityTracker.addMovement(vtev);eventAddedToVelocityTracker = true;//1.根据过去的点计算现在的滑动速度mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);//最后一次 X/Y 轴的滑动速度final float xvel = canScrollHorizontally ? -mVelocityTracker.getXVelocity(mScrollPointerId) : 0;final float yvel = canScrollVertically ? -mVelocityTracker.getYVelocity(mScrollPointerId) : 0;//处理惯性滑动if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {setScrollState(SCROLL_STATE_IDLE);//设置滑动状态}resetScroll();//2.重置滑动} break;

Up事件在手指离开后,滑动事件结束。主要做了两件事:

  • 1.通过computeCurrentVelocity()计算滑动的速度以及计算X,Y轴的最后滑动速度,fling()是处理惯性滑动;
  • 2.惯性滑动结束后设置滑动状态,重置滑动信息。

先通过computeCurrentVelocity()计算滑动的速度以及计算X,Y轴最后的滑动速度后,如果抬起的时候最后速度大于系统的给定值,就保持惯性再滑动一段距离,最后通知嵌套滑动的View滑动结束,重置数据。fling()是处理惯性滑动的核心方法,下面会分析到。

4. Cancel事件

    case MotionEvent.ACTION_CANCEL:{//手势取消,释放各种资源cancelScroll();//退出滑动} break;private void cancelScroll() {//1.重置滑动,是否资源resetScroll();//2.设置滑动状态为没有滑动状态setScrollState(SCROLL_STATE_IDLE);}

Cancel事件表示手势事件被取消了,重置滑动状态等信息。主要做了两件事:

  • 1.resetScroll()停止正在进行的嵌套滑动,释放资源;
  • 2.设置滑动状态为SCROLL_STATE_IDLE没有滑动。

当事件中途被父View消费时会响应cancel事件,比如在RecyclerView接收到down事件,但是后续被父View拦截,RecyclerView就会响应cancel事件。

5. Pointer_Down事件

    case MotionEvent.ACTION_POINTER_DOWN:{//多个手指按下//更新mScrollPointerId,表示只会响应最近按下的手势事件mScrollPointerId = e.getPointerId(actionIndex);//更新最近的手势坐标mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f);mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f);} break;

Pointer_Down事件主要是在多个手指按下时,立即更新mScrollPointerId和按下的坐标。响应新的手势,不再响应旧的手势,一切事件和坐标以新的事件和坐标为准。

注意:这里多指滑动的意思不是RecyclerView响应多个手指滑动,而是当旧的一个手指没有释放时,此时另一个新的手指按下,那么RecyclerView就不响应旧手指的手势,而是响应最新手指的手势。

6. Pointer_Up事件

    case MotionEvent.ACTION_POINTER_UP:{//多个手指离开//选择一个最新的坐标点来处理结局,重新处理坐标onPointerUp(e);} break;private void onPointerUp(MotionEvent e) {final int actionIndex = e.getActionIndex();if (e.getPointerId(actionIndex) == mScrollPointerId) {final int newIndex = actionIndex == 0 ? 1 : 0;mScrollPointerId = e.getPointerId(newIndex);mInitialTouchX = mLastTouchX = (int) (e.getX(newIndex) + 0.5f);mInitialTouchY = mLastTouchY = (int) (e.getY(newIndex) + 0.5f);}}

Pointer_Up事件在多指离开时,选择一个最新的指针来处理结局。onPointerUp()判断离开的事件坐标id是否与当前的滑动坐标id一致,如果一致则更新手势坐标和当前坐标点id。

2.2、滑动流程

那么RecyclerView的onTouchEvent()方法相关的事件类型分析完了,下面看看RecyclerView在处理自身滑动时究竟做了什么?上一篇文章结合LinearLayoutManager的源码分析了RecyclerView的绘制流程,这里同样以LinearLayoutManager的垂直方向为例分析RecyclerView垂直方向的滑动,其他方式的滑动都是万变不离其宗。开始响应onTouchEvent()方法时获取滑动方向:

	//根据布局方向来决定滑动的方向final boolean canScrollHorizontally = mLayout.canScrollHorizontally();//能否支持水平方向滑动final boolean canScrollVertically = mLayout.canScrollVertically();//能否支持垂直方向滑动

上面是通过LinearLayoutManager获取是否能水平、垂直方向滑动,这里回调了mLayout.canScrollHorizontally()mLayout.canScrollVertically()方法,如果canScrollHorizontally = ture时,能左右滑动,如果canScrollVertically = true时,能上下滑动。

    @Overridepublic boolean canScrollHorizontally() {return mOrientation == HORIZONTAL;//线性方向为水平方向,能水平滑动}@Overridepublic boolean canScrollVertically() {return mOrientation == VERTICAL;//线性方向为垂直方向,能垂直滑动}

1. 普通滑动

在上面的Move事件分析知道,在ACTION_MOVE里面计算滑动的距离,然后调用scrollByInternal()处理itemView随着手势的移动而滑动,核心方法是scrollByInternal()

   boolean scrollByInternal(int x, int y, MotionEvent ev) {int unconsumedX = 0; int unconsumedY = 0;int consumedX = 0; int consumedY = 0;//1.使用延迟更改来避免滑动期间adapter更改可能引发的崩溃consumePendingUpdateOperations();if (mAdapter != null) {//2.滑动步骤scrollStep(x, y, mReusableIntPair);consumedX = mReusableIntPair[0];consumedY = mReusableIntPair[1];unconsumedX = x - consumedX;unconsumedY = y - consumedY;}//3.将嵌套的预滑动操作的一个步骤分派给当前嵌套的滑动父View,如果为true表示父View优先处理滑动事件。//如果消耗,dx dy会分别减去父View消耗的那一部分距离dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, mScrollOffset,TYPE_TOUCH, mReusableIntPair);unconsumedX -= mReusableIntPair[0];unconsumedY -= mReusableIntPair[1];boolean consumedNestedScroll = mReusableIntPair[0] != 0 || mReusableIntPair[1] != 0;//将滑动的偏移量考虑在内,更新最后的触摸坐标mLastTouchX -= mScrollOffset[0];mLastTouchY -= mScrollOffset[1];mNestedOffsets[0] += mScrollOffset[0];mNestedOffsets[1] += mScrollOffset[1];//4.滑动回调if (consumedX != 0 || consumedY != 0) {dispatchOnScrolled(consumedX, consumedY);}//是否有滑动消耗return consumedNestedScroll || consumedX != 0 || consumedY != 0;}

上面的代码主要做了四件事:

  • 1.consumePendingUpdateOperations(),使用延迟来避免滑动期间adapter更改可能引发的崩溃,因为滑动假定没有数据改变,但实际上数据已经更改;
  • 2.scrollStep()核心滑动步骤,交给布局管理器处理自身滑动;
  • 3.自身滑动完毕后仍采用嵌套的滑动机制通知父View优先处理滑动事件;
  • 4.dispatchOnScrolled()通知RecyclerView的滑动回调监听。

scrollStep()是处理自身滑动的方法,通过dx,dy来滑动RecyclerView,水平滑动则调用mLayout.scrollHorizontallyBy(),垂直滑动则调用mLayout.scrollVerticallyBy()

   void scrollStep(int dx, int dy, @Nullable int[] consumed) {if (dx != 0) {//在屏幕坐标中水平滑动dx像素,并返回移动的距离,默认不移动,返回为0consumedX = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);}if (dy != 0) {//在屏幕坐标中垂直滑动dy像素,并返回移动的距离,默认不移动,返回为0consumedY = mLayout.scrollVerticallyBy(dy, mRecycler, mState);}}

最终滑动的距离由LayoutManager处理滑动函数,这里看垂直方向的滑动scrollVerticallyBy()

    @Overridepublic int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler,RecyclerView.State state) {if (mOrientation == HORIZONTAL) {//如果是水平方向,则垂直方向的滑动距离为0,即不滑动return 0;}return scrollBy(dy, recycler, state);}

scrollVerticallyBy()是垂直方向的滑动,如果线性方向为HORIZONTAL,则滑动距离为0,即不滑动,否则调用scrollBy()实现垂直方向的滑动:

  int scrollBy(int delta, RecyclerView.Recycler recycler, RecyclerView.State state) {if (getChildCount() == 0 || delta == 0) {//如果没有数据或者滑动距离为0,则不滑动return 0;}//1.更新布局状态updateLayoutState(layoutDirection, absDelta, true, state);//2.先调用fill()把滑进来的view布局进来,并回收滑出去的view,返回当前布局View的空间final int consumed = mLayoutState.mScrollingOffset + fill(recycler, mLayoutState, state, false);//计算滑动的距离final int scrolled = absDelta > consumed ? layoutDirection * consumed : delta;//3.给所有子View添加偏移量,按照计算滑动的距离动距离移动View的位置mOrientationHelper.offsetChildren(-scrolled);//移动mLayoutState.mLastScrollDelta = scrolled;//记录本次滑动的距离return scrolled;}

这两个方法主要做三件事,

  • 1.通过updateLayoutState()修正了一些状态,比如描点在哪里,是否有动画等;
  • 2.通过fill()先检查有哪些view超出边界,进行回收,然后重新填充新的view,并返回填充的偏移量;
  • 3.通过offsetChildren()给所有子View添加偏移量,按照滑动距离移动View的位置。

scrollBy()处理滑动的逻辑就是先更新布局的状态,然后调用fill()函数返回填充的距离,同时如果有滑动距离则把View布局进来,如果一个View被完全移出屏幕则回收到缓存中,最后计算滑动距离调用offsetChildren()给所有子view进行偏移

注意:滑动事件并不会重新请求布局,不会重新onLayoutChildren(),对布局的更新是通过fill()重新从缓存获取或者创建一个itemView填充到屏幕。

我们来看看offsetChildren()移动itemView的方法,在OrientationHelper帮助类里面找到offsetChildren()的抽象方法,那么我们得去实现类中找到实现这个方法的逻辑:

	//通过给出的距离移动所有的子VIewpublic abstract void offsetChildren(int amount);

在LinerLayoutManager源码里面实现了OrientationHelper帮助类并实现了抽象方法:

  public static OrientationHelper createVerticalHelper(RecyclerView.LayoutManager layoutManager) {return new OrientationHelper(layoutManager) {@Overridepublic void offsetChildren(int amount) {mLayoutManager.offsetChildrenVertical(amount);//沿垂直方向偏移所有子View附加到RecyclerView中}};}

offsetChildrenVertical(int dx)是沿垂直方向偏移所有子View附加到RecyclerView中,也是回调LayoutManager中的offsetChildrenVertical()

   public void offsetChildrenVertical(@Px int dy) {if (mRecyclerView != null) {mRecyclerView.offsetChildrenVertical(dy);}}

跟进去又回到RecyclerView的offsetChildrenVertical()

	public void offsetChildrenVertical(@Px int dy) {//获取RecyclerView的ItemView个数final int childCount = mChildHelper.getChildCount();//遍历所有ItemView,调用View的offsetTopAndBottom()进行滑动for (int i = 0; i < childCount; i++) {mChildHelper.getChildAt(i).offsetTopAndBottom(dy);//移动view多少像素}}

终于找到了核心移动子View的源码:**遍历所有ItemView,最终通过每个子View调用了底层View的offsetTopAndBottom()或者offsetLeftAndRight()方法来实现滑动的。**先获取到itemView的总数,然后通过遍历将每一个itemView移动指定的距离dy。

普通滑动总结:在RecyclerView的Move触摸事件分派滑动事件响应scrollByInternal()方法,处理父View嵌套滑动,实际上调用LayoutManager的scrollHorizontallyBy()或者scrollVerticallyBy()方法来计算scrollBy()fill()填充布局同时处理实际的滑动距离,遍历所有ItemView,最终通过每个子View调用了底层View的offsetTopAndBottom()或者offsetLeftAndRight()方法来实现滑动的。

2. 惯性滑动

我们在快速滑动列表然后松开手指,列表依然会持续惯性滑动一段时间,RecyclerView的惯性滑动fling(),在onTouchEvent()处理ACTION_UP事件的时候:

 case MotionEvent.ACTION_UP: {//手指离开,滑动事件结束mVelocityTracker.addMovement(vtev);//1.根据过去的点计算现在的滑动速度mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);//最后一次 X/Y 轴的滑动速度final float xvel = canScrollHorizontally ? -mVelocityTracker.getXVelocity(mScrollPointerId) : 0;final float yvel = canScrollVertically ? -mVelocityTracker.getYVelocity(mScrollPointerId) : 0;//处理惯性滑动if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {setScrollState(SCROLL_STATE_IDLE);//设置滑动状态}resetScroll();//2.重置滑动} break;

先通过computeCurrentVelocity()计算滑动的速度以及计算X,Y轴最后的滑动速度,如果抬起的时候最后速度大于系统的给定值,就保持惯性再滑动一段距离,最后通知嵌套滑动的View滑动已结束,重置滑动信息。惯性滑动核心方法fling()

    public boolean fling(int velocityX, int velocityY) {//1.能否水平、垂直方向滑动final boolean canScrollHorizontal = mLayout.canScrollHorizontally();final boolean canScrollVertical = mLayout.canScrollVertically();if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {velocityX = 0;//如果不能水平滑动,或者滑动速度小于系统的滑动速度,则水平滑动速度设置为0}if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {velocityY = 0;//如果不能垂直滑动,或者滑动速度小于系统的滑动速度,则垂直滑动速度设置为0}//没有滑动速度,返回false,不处理惯性滑动if (velocityX == 0 && velocityY == 0) return false;//父View是否处理嵌套预惯性滑动if (!dispatchNestedPreFling(velocityX, velocityY)) {final boolean canScroll = canScrollHorizontal || canScrollVertical;dispatchNestedFling(velocityX, velocityY, canScroll);//2.客户端按照开发者需求自己处理惯性滑动if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) {return true;}if (canScroll) {//如果能滑动startNestedScroll(nestedScrollAxis, TYPE_NON_TOUCH);//开始嵌套滑动//3.RecyclerView自己处理惯性滑动mViewFlinger.fling(velocityX, velocityY);return true;}}return false;}

fling()这里主要做了三件事:

  • 1.先根据滑动方向以及滑动速度与系统速度比较,判断能不能惯性滑动;
  • 2.客户端按照开发者要求自己处理惯性滑动,通过OnFlingListener.onFling()方法判断RecyclerView是否优处理开发者要求的惯性运动,在决定本身是否处理惯性滑动;
  • 3.RecyclerView自己处理惯性滑动,调用ViewFlinger的fling()方法。

优先处理开发者的惯性滑动,如果开发者不处理则RecyclerView处理自身惯性滑动,ViewFlinger是RecyclerView内部的一个Runnable类,接着ViewFlinger的fling()

    public void fling(int velocityX, int velocityY) {setScrollState(SCROLL_STATE_SETTLING);//设置滚动状态为惯性滑动mOverScroller = new OverScroller(getContext(), sQuinticInterpolator);//基于一个摇摆的手势开始滑动,所走的距离取决于初速度。mOverScroller.fling(0, 0, velocityX, velocityY,Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);//使Runnable在下一个动画时间步上执行,runnable将在用户界面线程上运行。postOnAnimation();}

mOverScroller.fling()只是计算惯性滑动的相关参数,最后调用了postOnAnimation()方法,它最终回调ViewFlinger的run方法:

    @Overridepublic void run() {······final OverScroller scroller = mOverScroller;//1.更新滑动位置信息,判断当前是否滑动完毕,true表示为未滑动完毕if (scroller.computeScrollOffset()) {final int x = scroller.getCurrX();final int y = scroller.getCurrY();//计算滚动距离int unconsumedX = x - mLastFlingX;int unconsumedY = y - mLastFlingY;mLastFlingX = x;mLastFlingY = y;int consumedX = 0;int consumedY = 0;······if (mAdapter != null) {//本地滑动mReusableIntPair[0] = 0;mReusableIntPair[1] = 0;//2.滑动步骤,通过dX,dY滑动RecyclerViewscrollStep(unconsumedX, unconsumedY, mReusableIntPair);consumedX = mReusableIntPair[0];consumedY = mReusableIntPair[1];unconsumedX -= consumedX;unconsumedY -= consumedY;}//嵌套后滑动mReusableIntPair[0] = 0;mReusableIntPair[1] = 0;//父View是否处理嵌套滑动事件dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, null,TYPE_NON_TOUCH, mReusableIntPair);unconsumedX -= mReusableIntPair[0];unconsumedY -= mReusableIntPair[1];boolean scrollerFinishedX = scroller.getCurrX() == scroller.getFinalX();boolean scrollerFinishedY = scroller.getCurrY() == scroller.getFinalY();//滑动是否完成(滑动结束或者x,y距离完成滑动或者无法进一步滑动)final boolean doneScrolling = scroller.isFinished()|| ((scrollerFinishedX || unconsumedX != 0)&& (scrollerFinishedY || unconsumedY != 0));//4.滑动结束if (!smoothScrollerPending && doneScrolling) {if (getOverScrollMode() != View.OVER_SCROLL_NEVER) {final int vel = (int) scroller.getCurrVelocity();int velX = unconsumedX < 0 ? -vel : unconsumedX > 0 ? vel : 0;int velY = unconsumedY < 0 ? -vel : unconsumedY > 0 ? vel : 0;absorbGlows(velX, velY);}if (ALLOW_THREAD_GAP_WORK) {mPrefetchRegistry.clearPrefetchPositions();}} else {//3.否则继续滑动(递归执行run方法,直到滑动结束为止)postOnAnimation();//预取ViewHolder(缓存中获取或者创建)if (mGapWorker != null) {mGapWorker.postFromTraversal(RecyclerView.this, consumedX, consumedY);}}}//重新滑动if (mReSchedulePostAnimationCallback) {internalPostOnAnimation();} else {//设置滑动结束状态setScrollState(SCROLL_STATE_IDLE);stopNestedScroll(TYPE_NON_TOUCH);}}

上面主要做了三件事:

  • 1.更新滑动位置信息,判断当前是否滑动完毕,true表示为未滑动完毕;
  • 2.计算滑动距离的相关信息,回调scrollStep()通过dX,dY滑动RecyclerView;
  • 3.如果滑动未结束,执行postOnAnimation()递归run方法,直到滑动结束为止;
  • 4.滑动结束,清除数据,设置滑动结束状态。

惯性滑动总结:在RecyclerView响应onTouchEvent()的up事件时,根据最后滑动速度判断是否有惯性滑动,如果有则通过fling()先处理开发者要求处理的惯性滑动,否则直接RecyclerView自身处理惯性滑动,在ViewFlinger的fling()计算滑动相关的坐标数据信息,然后在postOnAnimation()中回调run()处理滑动,也是调用scrollStep()完成滑动,如果滑动未结束则递归执行postOnAnimation()方法回调run()直接滑动完成。

2.3、滑动原理总结

RecyclerView的滑动事件处理依然是通过onTouchEvent()触控事件响应,计算更新触摸坐标以及滑动方向等相关信息,处理父View的嵌套滑动,滑动事件响应scrollByInternal()方法,实际上调用LayoutManager的scrollHorizontallyBy()或者scrollVerticallyBy()方法来计算在scrollBy()fill()填充布局同时处理实际的滑动距离,最后RecyclerView遍历所有ItemView,最终通过每个子View调用了底层View的offsetTopAndBottom()或者offsetLeftAndRight()方法来实现滑动的。

RecyclerView的滑动流程图如下(双击点开更高清): 深入理解 RecyclerView 的绘制流程和滑动原理