RecyclerView局部刷新和原理介绍
RecyclerView局部刷新和原理介紹
- 一、引言
- 二、局部刷新的正確使用姿勢
- 三、局部刷新的原理
- 3.0 前提
- 3.1 RecyclerView與Adapter建立觀察者模式
- 3.2 onItemRangeChanged()
- 3.3 dispatchLayoutStep1()
- 3.3.1 處理Adapter更新和確定會運行的動畫
- 3.3.2 記錄Views信息
- 3.3.2.1 記錄preLayout信息
- 3.3.2.2 記錄要發生改變等holder等信息
- 3.3.3 運行predictive layout,并保存它的信息
- 3.4 dispatchLayoutStep2()
- 3.5 dispatchLayoutStep3()
一、引言
Android早期實現列表功能的控件是ListView,后來google推出了RecyclerView替代ListView。RecyclerView相對ListView有一些優勢,其中一個是局部刷新,本文主要圍繞它進行介紹。
二、局部刷新的正確使用姿勢
對于局部刷新,我的理解是notifyDataChanged()方法是全部刷新,notifyItemChanged、notifyItemInserted、notifyItemRemoved等一系列方法只對相應位置的item進行刷新。但當我把之前代碼里的notifyDataChanged()方法替換為使用notifyItemChanged(int position)方法,來完成點贊按鈕狀態替換時,卻遇到了圖片閃爍的問題,如下圖所示:
經測試發現,notifyItemChanged(int position)方法導致Adapter的onBindViewHolder(@NonNull VH holder, int position)方法得到調用,但每次調用時holder和holder.itemView的hashCode值并不相同,也就是notifyItemChanged(int position)方法調用時,RecyclerView更換了position位置的View。
經過google發現,notifyItemChanged(int position)有一個重載方法,notifyItemChanged(int position, @Nullable Object payload),其實notifyItemChanged(int position)本質上調用的就是notifyItemChanged(int position, null)。這個方法可以用來實現更深一層的局部刷新:Item內部View的局部刷新。方法說明中關于payload介紹如下:
Client can optionally pass a payload for partial change. These payloads will be merged and may be passed to adapter’s onBindViewHolder(RecyclerView.ViewHolder, int, List) if the item is already represented by a ViewHolder and it will be rebound to the same ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing payloads on that item and prevent future payload until onBindViewHolder(RecyclerView.ViewHolder, int, List) is called. Adapter should not assume that the payload will always be passed to onBindViewHolder(), e.g. when the view is not attached, the payload will be simply dropped.
我把notifyItemChanged(int position)更改為notifyItemChanged(int position, @Nullable Object payload),果然沒有再出現圖片閃爍的問題,代碼如下:
adapter.notifyItemChanged(position, VideoRcmdListAdapter.UPDATE_REASON_LIKE)override fun onBindViewHolder(holder: BaseViewHolder<FeedCard>, position: Int, payloads: MutableList<Any>) {val updateByPayload = bindPosViewWithPayLoads(holder, items[position], payloads)if (!updateByPayload) {onBindViewHolder(holder, actualPosition)}}private fun bindPosViewWithPayLoads(holder: BaseViewHolder<FeedCard>, item: FeedCard, payloads: MutableList<Any>): Boolean {var updateByPayload = falsefor (payload in payloads) {if (payload == VideoRcmdListAdapter.UPDATE_REASON_LIKE && holder is FeedVideoRcmdViewHolder && item.videoCard != null) {holder.updateLikeCheckBos(item.videoCard.liked, item.videoCard.favorites)updateByPayload = true}}return updateByPayload}綜合而言,如果是item內部某部分更改,比如像這里只是更改喜歡按鈕的狀態,使用payload;如果是item整個都更改,比如item1更換為了item2,那直接使用notifyItemChanged(int position)就好。
三、局部刷新的原理
先說結論吧:
Adapter.notifyItemChanged(int position, @Nullable Object payload)方法會導致RecyclerView的onMeasure()和onLayout()方法調用。在onLayout()方法中會調用dispatchLayoutStep1()、dispatchLayoutStep2()和dispatchLayoutStep3()三個方法,其中dispatchLayoutStep1()將更新信息存儲到ViewHolder中,dispatchLayoutStep2()進行子View的布局,dispatchLayoutStep3()觸發動畫。在dispatchLayoutStep2()中,會通過DefaultItemAnimator的canReuseUpdatedViewHolder()方法判斷position處是否復用之前的ViewHolder,如果調用notifyItemChanged()時的payload不為空,則復用;否則,不復用。在dispatchLayoutStep3()中,如果position處的ViewHolder與之前的ViewHolder相同,則執行DefaultItemAnimator的move動畫;如果不同,則執行DefaultItemAnimator的change動畫,舊View動畫消失(alpha值從1到0),新View動畫展現(alpha值從0到1),這樣就出現了閃爍效果。
再說一點自己的認識:
1.可以直接調試:
由于項目中RecyclerView都是通過"compile com.android.support:recyclerview-v7:27.1.1"方式引入的,所以RecyclerView的代碼是可以直接調試的,不然直接只看代碼分析執行流程,還真是很難看下去。
2.RecyclerView、LinearLayoutManager、ChildHelper、AdapterHelper中都有靜態DEBUG變量,用來控制日志輸出的代碼,默認為false,但我通過反射將其設置為true,仍然沒有日志輸出。這是因為Android studio在代碼編譯時將永不會執行的代碼刪除了,如果不想被編譯器刪除,我能想到的復雜方法只有通過aop方式了。當然,直接把代碼拷入到項目中,將DEBUG默認值設為true更簡單。
3.RecyclerView的代碼很復雜,自己只看懂了一小部分,但也看到用了很多設計模式和數據結構,用得都很恰當,優雅,比如隨處可見的享元模式,ArrayMap、LongSparseArray等,很值得看看。
3.0 前提
這部分以第二部分的例子入手,主要介紹下RecyclerView使用LinearLayoutManager和DefaultItemAnimator,RecyclerView的layout_width和layout_height都聲明為"match_parent",RecyclerView未設置hasFixedSize且Adapter未設置HasStableIds時,notifyItemChanged(int position, @Nullable Object payload)的執行流程。notifyItemChanged()調用前頁面已經刷新完畢,調用后短時間內沒有其他操作。
3.1 RecyclerView與Adapter建立觀察者模式
從adapter.notifyItemChanged(int position, @Nullable Object payload)方法入手
public final void notifyItemChanged(int position, @Nullable Object payload) {mObservable.notifyItemRangeChanged(position, 1, payload); }其中mObservable為AdapterDataObservable類型的對象,它的notifyItemRangeChanged()方法如下:
public void notifyItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {// since onItemRangeChanged() is implemented by the app, it could do anything, including// removing itself from {@link mObservers} - and that could cause problems if// an iterator is used on the ArrayList {@link mObservers}.// to avoid such problems, just march thru the list in the reverse order.for (int i = mObservers.size() - 1; i >= 0; i--) {mObservers.get(i).onItemRangeChanged(positionStart, itemCount, payload);} }直接對mObservers列表進行遍歷,并調用其onItemRangeChanged()方法。向mObservers中添加Observer的方法為registerObserver()方法。
public void registerObserver(T observer) {if (observer == null) {throw new IllegalArgumentException("The observer is null.");}synchronized(mObservers) {if (mObservers.contains(observer)) {throw new IllegalStateException("Observer " + observer + " is already registered.");}mObservers.add(observer);}}RecyclerView中最終調用registerObserver的地方為setAdapterInternal()方法,這個方法又被setAdapter()和swapAdapter()調用,registerObserver()方法傳入的參數為RecyclerView的mObserver變量。
總結而言,RecyclerView通過調用setAdapter(adapter)方法,與adapter建立觀察者模式。當數據更改時,開發者通過adapter的notifyXXX()方法通知RecyclerView的mObserver變量進行UI更新。
3.2 onItemRangeChanged()
RecyclerView中的mObserver是RecyclerViewDataObserver類型的變量,看下它的onItemChanged()方法。
@Overridepublic void onItemRangeChanged(int positionStart, int itemCount, Object payload) {if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) { // ①triggerUpdateProcessor(); // ②}}直接調用了mAdapterHelper的onItemRangeChanged()方法。
boolean onItemRangeChanged(int positionStart, int itemCount, Object payload) {mPendingUpdates.add(obtainUpdateOp(UpdateOp.UPDATE, positionStart, itemCount, payload));return mPendingUpdates.size() == 1;}該方法將數據更新信息封裝為UpdateOp對象,并將其添加到mPendingUpdates列表中,如果列表中數目為1,則返回true,否則false。在3.0的前提下,由于是在列表已經刷新完成的情況下調用notifyItemChanged(),所以應該返回true,會調用triggerUpdateProcessor方法。
再看下triggerUpdateProcessor()方法
由于未設置hasFixedSize,直接調用requestLayout()方法。requestLayout()方法會導致RecyclerView的onMeasure()和onLayout()方法得到調用。看下RecyclerView的onMeasure()方法。
@Overrideprotected void onMeasure(int widthSpec, int heightSpec) {if (mLayout == null) {defaultOnMeasure(widthSpec, heightSpec);return;}if (mLayout.isAutoMeasureEnabled()) {final int widthMode = MeasureSpec.getMode(widthSpec);final int heightMode = MeasureSpec.getMode(heightSpec);/*** This specific call should be considered deprecated and replaced with* {@link #defaultOnMeasure(int, int)}. It can't actually be replaced as it could* break existing third party code but all documentation directs developers to not* override {@link LayoutManager#onMeasure(int, int)} when* {@link LayoutManager#isAutoMeasureEnabled()} returns true.*/mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);final boolean measureSpecModeIsExactly =widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY;if (measureSpecModeIsExactly || mAdapter == null) {return;}// ...省略無關代碼} else {// ...省略無關代碼}mLayout是LinearLayoutManager類的對象,LinearLayoutManager的isAutoMeasureEnabled()為true;RecyclerView的寬高被設置為match_parent,因此widthMode和heightMode都為MeasureSpec.EXACTLY,進而measureSpecModeIsExactly為true。整個onMeasure()方法其實只調用了LayoutManager的onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec)方法,最終調用的是RecyclerView的defaultOnMeasure()方法,在RecyclerView寬高被設置為match_parent時等價于:
/*** An implementation of {@link View#onMeasure(int, int)} to fall back to in various scenarios* where this RecyclerView is otherwise lacking better information.*/void defaultOnMeasure(int widthSpec, int heightSpec) {// calling LayoutManager here is not pretty but that API is already public and it is better// than creating another method since this is internal.final int width = View.MeasureSpec.getSize(widthSpec);final int height = View.MeasureSpec.getSize(heightSpec);setMeasuredDimension(width, height);}因此圖片閃爍問題的原因只能去onLayout()方法中查找。RecyclerView的onLayout()方法直接調用了dispatchLayout()方法,去除無關代碼后如下:
void dispatchLayout() {if (mState.mLayoutStep == State.STEP_START) {dispatchLayoutStep1();dispatchLayoutStep2();} else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth() || mLayout.getHeight() != getHeight()) {dispatchLayoutStep2();} else {mLayout.setExactMeasureSpecsFrom(this);}dispatchLayoutStep3();}在3.0的前提下,mState.mLayoutStep為State.STEP_START,因此會依序執行dispatchLayoutStep1()、dispatchLayoutStep2()、dispatchLayoutStep3()三個方法。
3.3 dispatchLayoutStep1()
先看下dispatchLayoutStep1()的簡化代碼,
/*** The first step of a layout where we;* - process adapter updates* - decide which animation should run* - save information about current views* - If necessary, run predictive layout and save its information*/private void dispatchLayoutStep1() {mViewInfoStore.clear();processAdapterUpdatesAndSetAnimationFlags(); //① ②mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;mItemsAddedOrRemoved = mItemsChanged = false;mState.mInPreLayout = mState.mRunPredictiveAnimations;if (mState.mRunSimpleAnimations) { // Step 0: Find out where all non-removed items are, pre-layoutint 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());mViewInfoStore.addToPreLayout(holder, animationInfo);if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()&& !holder.shouldIgnore() && !holder.isInvalid()) {long key = getChangedHolderKey(holder);// This is NOT the only place where a ViewHolder is added to old change holders// list. There is another case where:// * A VH is currently hidden but not deleted// * The hidden item is changed in the adapter// * Layout manager decides to layout the item in the pre-Layout pass (step1)// When this case is detected, RV will un-hide that view and add to the old// change holders list.mViewInfoStore.addToOldChangeHolders(key, holder);// ③}}}if (mState.mRunPredictiveAnimations) { // Step 1: run prelayout: This will use the old positions of items. The layout manager// is expected to layout everything, even removed items (though not to add removed// items back to the container). This gives the pre-layout position of APPEARING views// which come into existence as part of the real layout.// Save old positions so that LayoutManager can run its mapping logic.saveOldPositions();final boolean didStructureChange = mState.mStructureChanged;mState.mStructureChanged = false;// temporarily disable flag because we are asking for previous layoutmLayout.onLayoutChildren(mRecycler, mState); // ④mState.mStructureChanged = didStructureChange;for (int i = 0; i < mChildHelper.getChildCount(); ++i) {final View child = mChildHelper.getChildAt(i);final ViewHolder viewHolder = getChildViewHolderInt(child);if (viewHolder.shouldIgnore()) {continue;}if (!mViewInfoStore.isInPreLayout(viewHolder)) {int flags = ItemAnimator.buildAdapterChangeFlagsForAnimations(viewHolder);boolean wasHidden = viewHolder.hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);if (!wasHidden) {flags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;}final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation(mState, viewHolder, flags, viewHolder.getUnmodifiedPayloads());if (wasHidden) {recordAnimationInfoIfBouncedHiddenView(viewHolder, animationInfo);} else {mViewInfoStore.addToAppearedInPreLayoutHolders(viewHolder, animationInfo);}}}// we don't process disappearing list because they may re-appear in post layout pass.clearOldPositions();} else {clearOldPositions();}mState.mLayoutStep = State.STEP_LAYOUT;}對于第二部分的例子而言,該方法做了四件事,這四件事代碼作者都寫在方法的注釋里了:
* - process adapter updates 處理Adapter更新,將3.2中AdapterHelper里的mPendingUpdates中的內容存儲到ViewHolder中
* - decide which animation should run 確定會運行的動畫
* - save information about current views 記錄當前Views的信息
* - If necessary, run predictive layout and save its information 運行predictive layout,并保存它的信息
看下這四步都分別做了什么:
3.3.1 處理Adapter更新和確定會運行的動畫
這兩步都在processAdapterUpdatesAndSetAnimationFlags()方法中,
/*** Consumes adapter updates and calculates which type of animations we want to run.* Called in onMeasure and dispatchLayout.* <p>* This method may process only the pre-layout state of updates or all of them.*/private void processAdapterUpdatesAndSetAnimationFlags() {// simple animations are a subset of advanced animations (which will cause a// pre-layout step)// If layout supports predictive animations, pre-process to decide if we want to run themif (predictiveItemAnimationsEnabled()) { // ① mAdapterHelper.preProcess(); // ② } else {mAdapterHelper.consumeUpdatesInOnePass();}boolean animationTypeSupported = mItemsAddedOrRemoved || mItemsChanged; // truemState.mRunSimpleAnimations = mFirstLayoutComplete // true&& mItemAnimator != null // 默認為DefaultItemAnimator,true&& (mDataSetHasChangedAfterLayout|| animationTypeSupported // true|| mLayout.mRequestedSimpleAnimations)&& (!mDataSetHasChangedAfterLayout // true|| mAdapter.hasStableIds()); // ③ truemState.mRunPredictiveAnimations = mState.mRunSimpleAnimations // true&& animationTypeSupported // true&& !mDataSetHasChangedAfterLayout // true&& predictiveItemAnimationsEnabled(); // ④ true}① 是判斷是否允許predictiveItemAnimations,predictive animation介紹,對于3.0前提下的LinearLayoutManager而言為true。
② 將3.2中AdapterHelper里的mPendingUpdates中的內容存儲到ViewHolder中。
重點看下mAdapterHelper的preProcess()方法
從3.2處的分析可知,mPendingUpdates列表中只包含一個cmd為UpdateOp.UPDATE的UpdateOp,因此只調用了一次applyUpdate(op)方法并將mPendingUpdates清空,看下AdapterHelper.applyUpdate()方法:
private void applyUpdate(UpdateOp op) {int tmpStart = op.positionStart;int tmpCount = 0;int tmpEnd = op.positionStart + op.itemCount;int type = -1;for (int position = op.positionStart; position < tmpEnd; position++) {RecyclerView.ViewHolder vh = mCallback.findViewHolder(position); // vh不為null,trueif (vh != null || canFindInPreLayout(position)) { // deferredif (type == POSITION_TYPE_INVISIBLE) {UpdateOp newOp = obtainUpdateOp(UpdateOp.UPDATE, tmpStart, tmpCount,op.payload);dispatchAndUpdateViewHolders(newOp);tmpCount = 0;tmpStart = position;}type = POSITION_TYPE_NEW_OR_LAID_OUT; // POSITION_TYPE_NEW_OR_LAID_OUT值為1} tmpCount++;}// 省略部分代碼if (type == POSITION_TYPE_INVISIBLE) {dispatchAndUpdateViewHolders(op);} else {postponeAndUpdateViewHolders(op);}}mCallback變量是在RecyclerView構造函數中初始化AdapterHelper變量時創建的,由于執行applyUpdate的View是顯示的,所以vh值不為null。因此type為POSITION_TYPE_NEW_OR_LAID_OUT,進而調用了postponeAndUpdateViewHolders()方法。
private void postponeAndUpdateViewHolders(UpdateOp op) {mPostponedList.add(op); // ①switch (op.cmd) {case UpdateOp.ADD:mCallback.offsetPositionsForAdd(op.positionStart, op.itemCount);break;case UpdateOp.MOVE:mCallback.offsetPositionsForMove(op.positionStart, op.itemCount);break;case UpdateOp.REMOVE:mCallback.offsetPositionsForRemovingLaidOutOrNewView(op.positionStart,op.itemCount);break;case UpdateOp.UPDATE:mCallback.markViewHoldersUpdated(op.positionStart, op.itemCount, op.payload); // ②break;default:throw new IllegalArgumentException("Unknown update op type for " + op);}}postponeAndUpdateViewHolders()做了兩件事,① 將UpdateOp存入mPostponedList中,② 調用mCallback的markViewHoldersUpdated方法,markViewHoldersUpdated()方法如下:
@Overridepublic void markViewHoldersUpdated(int positionStart, int itemCount, Object payload) {viewRangeUpdate(positionStart, itemCount, payload); // ①// 此處可以回到processAdapterUpdatesAndSetAnimationFlags和dispatchLayoutStep1中看下mItemsChanged使用的地方mItemsChanged = true; // ②}做了兩件事,① 調用viewRangeUpdate()方法,② 將mItemsChanged變量置為true。
/*** Rebind existing views for the given range, or create as needed.** @param positionStart Adapter position to start at* @param itemCount Number of views that must explicitly be rebound*/void viewRangeUpdate(int positionStart, int itemCount, Object payload) {final int childCount = mChildHelper.getUnfilteredChildCount();final int positionEnd = positionStart + itemCount;for (int i = 0; i < childCount; i++) {final View child = mChildHelper.getUnfilteredChildAt(i);final ViewHolder holder = getChildViewHolderInt(child);if (holder == null || holder.shouldIgnore()) {continue;}if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) {// We re-bind these view holders after pre-processing is complete so that// ViewHolders have their final positions assigned.holder.addFlags(ViewHolder.FLAG_UPDATE);holder.addChangePayload(payload);// lp cannot be null since we get ViewHolder from it.((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;}}mRecycler.viewRangeUpdate(positionStart, itemCount);}viewRangeUpdate()方法完成了將mPendingUpdates列表里的更新存儲到相應的ViewHolder中的功能:添加ViewHolder.FLAG_UPDATE的flag,表示該ViewHolder要發生改變,之后該viewHolder的isUpdated()和needsUpdate()方法將返回true;將payload保存到holder的mPayloads列表中。
回到processAdapterUpdatesAndSetAnimationFlags()中,由于mItemsChanged在markViewHoldersUpdated()方法中被置為true,所以animationTypeSupported變量為true,同時由于mFirstLayoutComplete為true,mItemAnimator默認為DefaultItemAnimator,不為null,mDataSetHasChangedAfterLayout為false,所以③ 處mState.mRunSimpleAnimations也為true。在④處,mState.mRunPredictiveAnimations也為true。
3.3.2 記錄Views信息
回到dispatchLayoutStep1()中
mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;mItemsAddedOrRemoved = mItemsChanged = false;mState.mInPreLayout = mState.mRunPredictiveAnimations;mState.mItemCount = mAdapter.getItemCount();findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);if (mState.mRunSimpleAnimations) {// Step 0: Find out where all non-removed items are, pre-layoutint count = mChildHelper.getChildCount();for (int i = 0; i < count; ++i) {final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {continue;}final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation(mState, holder,ItemAnimator.buildAdapterChangeFlagsForAnimations(holder),holder.getUnmodifiedPayloads());mViewInfoStore.addToPreLayout(holder, animationInfo);if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()&& !holder.shouldIgnore() && !holder.isInvalid()) {long key = getChangedHolderKey(holder);// This is NOT the only place where a ViewHolder is added to old change holders// list. There is another case where:// * A VH is currently hidden but not deleted// * The hidden item is changed in the adapter// * Layout manager decides to layout the item in the pre-Layout pass (step1)// When this case is detected, RV will un-hide that view and add to the old// change holders list.mViewInfoStore.addToOldChangeHolders(key, holder);}}}由于processAdapterUpdatesAndSetAnimationFlags()方法中mState.mRunSimpleAnimations為true,且viewRangeUpdate()方法中將
mItemsChanged變量設置為true,所以mState.mTrackOldChangeHolders變量為true,mState.mInPreLayout也為true。由于mState.mRunSimpleAnimations為true,會對RecyclerView中的ChildView進行遍歷,從view中取出holder,并記錄所有holder到preLayout信息和要發生改變的holder的信息。
3.3.2.1 記錄preLayout信息
看下ViewInfoStore的addPreLayout()方法,將holder和animationInfo存入到mLayoutHolderMap中。
/*** Adds the item information to the prelayout tracking* @param holder The ViewHolder whose information is being saved* @param info The information to save*/void addToPreLayout(ViewHolder holder, ItemHolderInfo info) {InfoRecord record = mLayoutHolderMap.get(holder);if (record == null) {record = InfoRecord.obtain();// mLayoutHolderMap為ArrayMap類型mLayoutHolderMap.put(holder, record); }record.preInfo = info;record.flags |= FLAG_PRE;}3.3.2.2 記錄要發生改變等holder等信息
對于3.3.1中viewRangeUpdate()方法中處理過的ViewHolder,holder.isUpdated()為true,holder.isRemoved()、holder.shouldIgnore()、holder.isInvalid()都為false,所以會存入到ViewInfoStore的mOldChangedHolders中,這個會在dispatchLayoutStep3()中用到。
if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()&& !holder.shouldIgnore() && !holder.isInvalid()) {long key = getChangedHolderKey(holder);mViewInfoStore.addToOldChangeHolders(key, holder);}3.3.3 運行predictive layout,并保存它的信息
mState.mInPreLayout = mState.mRunPredictiveAnimations; //... 省略部分代碼 mLayout.onLayoutChildren(mRecycler, mState);此處的mLayout為LinearLayoutManager類型的對象,看下LinearLayoutManager的onLayoutChildren()方法,省略無關代碼后如下。
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {// layout algorithm:// 1) by checking children and other variables, find an anchor coordinate and an anchor// item position.// 2) fill towards start, stacking from bottom// 3) fill towards end, stacking from top// 4) scroll to fulfill requirements like stack from bottom.// create layout statefinal View focused = getFocusedChild();if (!mAnchorInfo.mValid || mPendingScrollPosition != NO_POSITION|| mPendingSavedState != null) {mAnchorInfo.reset();mAnchorInfo.mLayoutFromEnd = mShouldReverseLayout ^ mStackFromEnd;// calculate anchor position and coordinateupdateAnchorInfoForLayout(recycler, state, mAnchorInfo); // ① 尋找錨點mAnchorInfo.mValid = true;} else if (focused != null && (mOrientationHelper.getDecoratedStart(focused)>= mOrientationHelper.getEndAfterPadding()|| mOrientationHelper.getDecoratedEnd(focused)<= mOrientationHelper.getStartAfterPadding())) {// This case relates to when the anchor child is the focused view and due to layout// shrinking the focused view fell outside the viewport, e.g. when soft keyboard shows// up after tapping an EditText which shrinks RV causing the focused view (The tapped// EditText which is the anchor child) to get kicked out of the screen. Will update the// anchor coordinate in order to make sure that the focused view is laid out. Otherwise,// the available space in layoutState will be calculated as negative preventing the// focused view from being laid out in fill.// Note that we won't update the anchor position between layout passes (refer to// TestResizingRelayoutWithAutoMeasure), which happens if we were to call// updateAnchorInfoForLayout for an anchor that's not the focused view (e.g. a reference// child which can change between layout passes).mAnchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused));}detachAndScrapAttachedViews(recycler); // ② 將RecyclerView中的所有View detach并回收mLayoutState.mInfinite = resolveIsInfinite();mLayoutState.mIsPreLayout = state.isPreLayout();if (mAnchorInfo.mLayoutFromEnd) {// ...省略無關代碼} else {// fill towards endupdateLayoutStateToFillEnd(mAnchorInfo);mLayoutState.mExtra = extraForEnd;fill(recycler, mLayoutState, state, false); // ③ 重新attach view,并鋪滿屏幕endOffset = mLayoutState.mOffset;final int lastElement = mLayoutState.mCurrentPosition;if (mLayoutState.mAvailable > 0) {extraForStart += mLayoutState.mAvailable;}// fill towards startupdateLayoutStateToFillStart(mAnchorInfo);mLayoutState.mExtra = extraForStart;mLayoutState.mCurrentPosition += mLayoutState.mItemDirection;fill(recycler, mLayoutState, state, false);startOffset = mLayoutState.mOffset;if (mLayoutState.mAvailable > 0) {extraForEnd = mLayoutState.mAvailable;// start could not consume all it should. add more items towards endupdateLayoutStateToFillEnd(lastElement, endOffset);mLayoutState.mExtra = extraForEnd;fill(recycler, mLayoutState, state, false);endOffset = mLayoutState.mOffset;}}// ...省略無關代碼}onLayoutChildren()做了三件事:①尋找錨點;②將RecyclerView中的所有View detach并回收;③重新attach view,并鋪滿屏幕。
重點關注下②和③。
看下②中detachAndScrapAttachedViews()方法。
遍歷RecyclerView的所有child,并執行scrapOrRecycleView()方法。
private void scrapOrRecycleView(Recycler recycler, int index, View view) {final ViewHolder viewHolder = getChildViewHolderInt(view);if (viewHolder.isInvalid() && !viewHolder.isRemoved()&& !mRecyclerView.mAdapter.hasStableIds()) {removeViewAt(index);recycler.recycleViewHolderInternal(viewHolder);} else {detachViewAt(index); // ①recycler.scrapView(view); // ②mRecyclerView.mViewInfoStore.onViewDetached(viewHolder); // ③}}由于使用notifyItemChanged()做局部刷新,所以viewHolder.isInvalid()為false,因此會執行①②③,重點關注下①和②。
看下detachViewAt(int index)方法及其內部調用到的方法。
可以看到detachViewAt(int index)方法,一共做了三件事,需要關注的是ViewHolder添加FLAG_TMP_DETACHED這個flag,另外調用了ViewGroup的detachViewFromParent()方法,暫時將View從ViewGroup的mChildren數組中清除,并將View的parent置為null。
回到scrapOrRecycleView()方法,看下② Recycler.scrapView()方法及其調用的方法。
從SimpleItemAnimator的canReuseUpdatedViewHolder()方法看起,由于mSupportsChangeAnimations默認值為true,除非調用setSupportsChangeAnimations將其設置為false;同時在notifyItemChanged()的情況下,viewHolder.isInvalid()為false。所以SimpleItemAnimator的canReuseUpdatedViewHolder方法返回false。那么對于DefaultItemAnimator的canReuseUpdatedViewHolder()方法,返回值就完全取決于!payloads.isEmpty()的值,如果payloads為空,則返回false;如果payloads不為空,則返回true?;氐絪crapView(View)方法中,對于要update的ViewHolder(ViewHolder.isUpdated()為true),如果payloads為空,ViewHolder會被添加到mChangedScrap列表中,并將ViewHolder的mInChangeScrap變量設置為true,否則會添加到mAttachedScrap列表中并將ViewHolder的mInChangeScrap變量設置為false。
回到LinearLayoutManager中的onLayoutChildren()方法中,看下fill()方法。fill方法中不停調用layoutChunk()方法添加View,直到屏幕占滿。
注意看下layoutState的next()方法,這里有很多熟悉的方法,比如createViewHolder,bindViewHolder。
// 以下代碼在LinearLayoutManager.LayoutState中/*** Gets the view for the next element that we should layout.* Also updates current item index to the next item, based on {@link #mItemDirection}** @return The next element that we should layout.*/View next(RecyclerView.Recycler recycler) {// 此處mScrapList為nullif (mScrapList != null) { return nextViewFromScrapList();}// 從Recycler中獲取View,Recycler中有mAttachedScrap、mChangedScrap、mCachedViews三個List,還有ViewCacheExtension,RecyclerViewPoolfinal View view = recycler.getViewForPosition(mCurrentPosition); mCurrentPosition += mItemDirection;return view;}// 以下代碼在RecylcerView.Recycler中/*** Obtain a view initialized for the given position.** This method should be used by {@link LayoutManager} implementations to obtain* views to represent data from an {@link Adapter}.* <p>* The Recycler may reuse a scrap or detached view from a shared pool if one is* available for the correct view type. If the adapter has not indicated that the* data at the given position has changed, the Recycler will attempt to hand back* a scrap view that was previously initialized for that data without rebinding.** @param position Position to obtain a view for* @return A view representing the data at <code>position</code> from <code>adapter</code>*/public View getViewForPosition(int position) {return getViewForPosition(position, false);}View getViewForPosition(int position, boolean dryRun) {return tryGetViewHolderForPositionByDeadline(position, dryRun, FOREVER_NS).itemView;}/*** Attempts to get the ViewHolder for the given position, either from the Recycler scrap,* cache, the RecycledViewPool, or creating it directly.* <p>* If a deadlineNs other than {@link #FOREVER_NS} is passed, this method early return* rather than constructing or binding a ViewHolder if it doesn't think it has time.* If a ViewHolder must be constructed and not enough time remains, null is returned. If a* ViewHolder is aquired and must be bound but not enough time remains, an unbound holder is* returned. Use {@link ViewHolder#isBound()} on the returned object to check for this.** @param position Position of ViewHolder to be returned.* @param dryRun True if the ViewHolder should not be removed from scrap/cache/* @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should* complete. If FOREVER_NS is passed, this method will not fail to* create/bind the holder if needed.** @return ViewHolder for requested position*/@NullableViewHolder tryGetViewHolderForPositionByDeadline(int position,boolean dryRun, long deadlineNs) {boolean fromScrapOrHiddenOrCache = false;ViewHolder holder = null;// 0) If there is a changed scrap, try to find from thereif (mState.isPreLayout()) { // 還記得dispatchLayoutStep1中的mState.mInPreLayout = mState.mRunPredictiveAnimations;嗎?所以在dispatchLayoutStep1中會先從mChangedScrap中找viewHolder,可以回顧下scrapView()方法。holder = getChangedScrapViewForPosition(position); // ① fromScrapOrHiddenOrCache = holder != null;}// 1) Find by position from scrap/hidden list/cacheif (holder == null) {holder = getScrapOrHiddenOrCachedHolderForPosition(position, dryRun); // ②if (holder != null) {if (!validateViewHolderForOffsetPosition(holder)) {// recycle holder (and unscrap if relevant) since it can't be usedif (!dryRun) {// we would like to recycle this but need to make sure it is not used by// animation logic etc.holder.addFlags(ViewHolder.FLAG_INVALID);if (holder.isScrap()) {removeDetachedView(holder.itemView, false);holder.unScrap();} else if (holder.wasReturnedFromScrap()) {holder.clearReturnedFromScrapFlag();}recycleViewHolderInternal(holder);}holder = null;} else {fromScrapOrHiddenOrCache = true;}}}// ...省略后續boolean bound = false;if (mState.isPreLayout() && holder.isBound()) { // do not update unless we absolutely have to.holder.mPreLayoutPosition = position;} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {final int offsetPosition = mAdapterHelper.findPositionOffset(position);// 主要調用了mAdapter.bindViewHolder(holder, offsetPosition);// 進而調用了onBindViewHolder(holder, position, holder.getUnmodifiedPayloads());和holder.clearPayload();bound = tryBindViewHolderByDeadline(holder, offsetPosition, position, deadlineNs); // ⑦}// ...省略后續return holder;}ViewHolder getChangedScrapViewForPosition(int position) {// If pre-layout, check the changed scrap for an exact match.final int changedScrapSize;if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) {return null;}// find by positionfor (int i = 0; i < changedScrapSize; i++) {final ViewHolder holder = mChangedScrap.get(i);if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) {holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);return holder;}}return null;}/*** Returns a view for the position either from attach scrap, hidden children, or cache.** @param position Item position* @param dryRun Does a dry run, finds the ViewHolder but does not remove* @return a ViewHolder that can be re-used for this position.*/ViewHolder getScrapOrHiddenOrCachedHolderForPosition(int position, boolean dryRun) {final int scrapCount = mAttachedScrap.size();// Try first for an exact, non-invalid match from scrap.for (int i = 0; i < scrapCount; i++) {final ViewHolder holder = mAttachedScrap.get(i);if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position&& !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);return holder;}}if (!dryRun) {View view = mChildHelper.findHiddenNonRemovedView(position);if (view != null) {// This View is good to be used. We just need to unhide, detach and move to the// scrap list.final ViewHolder vh = getChildViewHolderInt(view);mChildHelper.unhide(view);int layoutIndex = mChildHelper.indexOfChild(view);if (layoutIndex == RecyclerView.NO_POSITION) {throw new IllegalStateException("layout index should not be -1 after "+ "unhiding a view:" + vh + exceptionLabel());}mChildHelper.detachViewFromParent(layoutIndex);scrapView(view);vh.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP| ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);return vh;}}// Search in our first-level recycled view cache.final int cacheSize = mCachedViews.size();for (int i = 0; i < cacheSize; i++) {final ViewHolder holder = mCachedViews.get(i);// invalid view holders may be in cache if adapter has stable ids as they can be// retrieved via getScrapOrCachedViewForIdif (!holder.isInvalid() && holder.getLayoutPosition() == position) {if (!dryRun) {mCachedViews.remove(i);}return holder;}}return null;}分析下layoutState的next()方法:從3.3.2可知,mState.isPreLayout()為true,所以會①先從mChangedScrap列表中查找ViewHolder,如果未找到,則②會從mAttachedScrap列表中查找?;仡櫹聅crapView()方法,RecyclerView中View所在的viewHolder不是存進mChangedScrap就是存進mAttachedScrap了。所以,對于notifyItemChanged()這種情況,在pre layout階段,經過這①②這兩步,holder的值就不為空了,由于mState.isPreLayout()為true,且holder.isBound()為true,所以不會執行bindViewHolder操作。
回到layoutChunk()方法,當next()獲取到view后,會執行RecyclerView的addView()方法。
對于此種情況,執行了如下代碼,跟scrapOrRecycleView()方法其實非常對稱。
holder.unScrap(); mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false);當所有RecyclerView添加完View,dispatchLayoutStep1()方法就執行完了,之后就開始執行dispatchLayoutStep2()方法。
3.4 dispatchLayoutStep2()
/*** The second layout step where we do the actual layout of the views for the final state.* This step might be run multiple times if necessary (e.g. measure).*/private void dispatchLayoutStep2() {mAdapterHelper.consumeUpdatesInOnePass(); // ①mState.mItemCount = mAdapter.getItemCount();mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;// Step 2: Run layoutmState.mInPreLayout = false;mLayout.onLayoutChildren(mRecycler, mState); // ②mState.mStructureChanged = false;// onLayoutChildren may have caused client code to disable item animations; re-checkmState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;mState.mLayoutStep = State.STEP_ANIMATIONS;}dispatchLayoutStep2()是真正進行布局的方法。3.0的前提下,①中什么都沒做,就不分析了。重點是3.3.3中花了很長代碼介紹的onLayoutChildren()方法,現在再次遇到就相對容易看了。dispatchLayoutStep2()中的onLayoutChildren與3.3.3中pre layout的不同之處,在于mState.mInPreLayout被設置為false了,造成的區別在tryGetViewHolderForPositionByDeadline()中。
/*** Attempts to get the ViewHolder for the given position, either from the Recycler scrap,* cache, the RecycledViewPool, or creating it directly.* <p>* If a deadlineNs other than {@link #FOREVER_NS} is passed, this method early return* rather than constructing or binding a ViewHolder if it doesn't think it has time.* If a ViewHolder must be constructed and not enough time remains, null is returned. If a* ViewHolder is aquired and must be bound but not enough time remains, an unbound holder is* returned. Use {@link ViewHolder#isBound()} on the returned object to check for this.** @param position Position of ViewHolder to be returned.* @param dryRun True if the ViewHolder should not be removed from scrap/cache/* @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should* complete. If FOREVER_NS is passed, this method will not fail to* create/bind the holder if needed.** @return ViewHolder for requested position*/@NullableViewHolder tryGetViewHolderForPositionByDeadline(int position,boolean dryRun, long deadlineNs) {boolean fromScrapOrHiddenOrCache = false;ViewHolder holder = null;// 0) If there is a changed scrap, try to find from thereif (mState.isPreLayout()) { holder = getChangedScrapViewForPosition(position); // ① fromScrapOrHiddenOrCache = holder != null;}// 1) Find by position from scrap/hidden list/cacheif (holder == null) {holder = getScrapOrHiddenOrCachedHolderForPosition(position, dryRun); // ②if (holder != null) {if (!validateViewHolderForOffsetPosition(holder)) {// recycle holder (and unscrap if relevant) since it can't be usedif (!dryRun) {// we would like to recycle this but need to make sure it is not used by// animation logic etc.holder.addFlags(ViewHolder.FLAG_INVALID);if (holder.isScrap()) {removeDetachedView(holder.itemView, false);holder.unScrap();} else if (holder.wasReturnedFromScrap()) {holder.clearReturnedFromScrapFlag();}recycleViewHolderInternal(holder);}holder = null;} else {fromScrapOrHiddenOrCache = true;}}}if (holder == null) {final int offsetPosition = mAdapterHelper.findPositionOffset(position);if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "+ "position " + position + "(offset:" + offsetPosition + ")."+ "state:" + mState.getItemCount() + exceptionLabel());}final int type = mAdapter.getItemViewType(offsetPosition);// 2) Find from scrap/cache via stable ids, if existsif (mAdapter.hasStableIds()) {holder = getScrapOrCachedViewForId(mAdapter.getItemId(offsetPosition),type, dryRun); // ③if (holder != null) {// update positionholder.mPosition = offsetPosition;fromScrapOrHiddenOrCache = true;}}if (holder == null && mViewCacheExtension != null) {// We are NOT sending the offsetPosition because LayoutManager does not// know it.final View view = mViewCacheExtension.getViewForPositionAndType(this, position, type); // ④if (view != null) {holder = getChildViewHolder(view);if (holder == null) {throw new IllegalArgumentException("getViewForPositionAndType returned"+ " a view which does not have a ViewHolder"+ exceptionLabel());} else if (holder.shouldIgnore()) {throw new IllegalArgumentException("getViewForPositionAndType returned"+ " a view that is ignored. You must call stopIgnoring before"+ " returning this view." + exceptionLabel());}}}if (holder == null) { // fallback to poolholder = getRecycledViewPool().getRecycledView(type); // ⑤if (holder != null) {holder.resetInternal();if (FORCE_INVALIDATE_DISPLAY_LIST) {invalidateDisplayListInt(holder);}}}if (holder == null) {// 看到了Adapter的createViewHolder方法,主要是調用了onCreateViewHolder方法// final VH holder = onCreateViewHolder(parent, viewType);holder = mAdapter.createViewHolder(RecyclerView.this, type); // ⑥if (ALLOW_THREAD_GAP_WORK) {// only bother finding nested RV if prefetchingRecyclerView innerView = findNestedRecyclerView(holder.itemView);if (innerView != null) {holder.mNestedRecyclerView = new WeakReference<>(innerView);}}}}// This is very ugly but the only place we can grab this information// before the View is rebound and returned to the LayoutManager for post layout ops.// We don't need this in pre-layout since the VH is not updated by the LM.if (fromScrapOrHiddenOrCache && !mState.isPreLayout() && holder.hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST)) {holder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);if (mState.mRunSimpleAnimations) {int changeFlags = ItemAnimator.buildAdapterChangeFlagsForAnimations(holder);changeFlags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;final ItemHolderInfo info = mItemAnimator.recordPreLayoutInformation(mState,holder, changeFlags, holder.getUnmodifiedPayloads());recordAnimationInfoIfBouncedHiddenView(holder, info);}}boolean bound = false;if (mState.isPreLayout() && holder.isBound()) { // do not update unless we absolutely have to.holder.mPreLayoutPosition = position;} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {final int offsetPosition = mAdapterHelper.findPositionOffset(position);// 主要調用了mAdapter.bindViewHolder(holder, offsetPosition);// 進而調用了onBindViewHolder(holder, position, holder.getUnmodifiedPayloads());和holder.clearPayload();bound = tryBindViewHolderByDeadline(holder, offsetPosition, position, deadlineNs); // ⑦}final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();final LayoutParams rvLayoutParams;if (lp == null) {rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();holder.itemView.setLayoutParams(rvLayoutParams);} else if (!checkLayoutParams(lp)) {rvLayoutParams = (LayoutParams) generateLayoutParams(lp);holder.itemView.setLayoutParams(rvLayoutParams);} else {rvLayoutParams = (LayoutParams) lp;}rvLayoutParams.mViewHolder = holder; // ⑧rvLayoutParams.mPendingInvalidate = fromScrapOrHiddenOrCache && bound;return holder;}由于mState.isPreLayout()為false,所以步驟①不會執行,也就是不會從mChangedScrap列表中查找,但使用notifyItemChanged(int position)方法進行刷新的ViewHolder,在scrapView()方法中被存入了mChangedScrap列表中,這就導致步驟②之后,holder 仍為null。之后的流程就是從緩存(cacheExtension、recyclerPool)中查找,如果查找到相同類型的ViewHolder,則從緩存中取出復用;如果沒有相同類型的ViewHolder,就只能通過onCreateViewHolder來創建新的viewHolder。但如果對于notifyItemChanged(int position, Object payload)方式進行刷新的ViewHolder,在scrapView()方法中被存入了mAttachedScrap列表中,經過步驟②后,就取得了之前的holder。這兩種情況的holder,在步驟⑦處,由于mState.isPreLayout()為false,且holder.needsUpdate() 為true,所以會調用onBindViewHolder(holder, position, holder.getUnmodifiedPayloads());來更新數據,回顧文章第二部分對onBindViewHolder(holder, position, payloads);的實現,可以看到此時喜歡的狀態就更新了。
在3.0的前提下,dispatchLayoutStep2()中onLayoutChildren()其他地方都與pre layout流程中onLayoutChildren()無區別。
3.5 dispatchLayoutStep3()
/*** The final step of the layout where we save the information about views for animations,* trigger animations and do any necessary cleanup.*/private void dispatchLayoutStep3() {mState.mLayoutStep = State.STEP_START;if (mState.mRunSimpleAnimations) {// Step 3: Find out where things are now, and process change animations.// traverse list in reverse because we may call animateChange in the loop which may// remove the target view holder.for (int i = mChildHelper.getChildCount() - 1; i >= 0; i--) {ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));if (holder.shouldIgnore()) {continue;}long key = getChangedHolderKey(holder);final ItemHolderInfo animationInfo = mItemAnimator.recordPostLayoutInformation(mState, holder);ViewHolder oldChangeViewHolder = mViewInfoStore.getFromOldChangeHolders(key); // ①if (oldChangeViewHolder != null && !oldChangeViewHolder.shouldIgnore()) {// run a change animation// If an Item is CHANGED but the updated version is disappearing, it creates// a conflicting case.// Since a view that is marked as disappearing is likely to be going out of// bounds, we run a change animation. Both views will be cleaned automatically// once their animations finish.// On the other hand, if it is the same view holder instance, we run a// disappearing animation instead because we are not going to rebind the updated// VH unless it is enforced by the layout manager.final boolean oldDisappearing = mViewInfoStore.isDisappearing(oldChangeViewHolder);final boolean newDisappearing = mViewInfoStore.isDisappearing(holder);if (oldDisappearing && oldChangeViewHolder == holder) {// run disappear animation instead of changemViewInfoStore.addToPostLayout(holder, animationInfo);} else {final ItemHolderInfo preInfo = mViewInfoStore.popFromPreLayout(oldChangeViewHolder);// we add and remove so that any post info is merged.mViewInfoStore.addToPostLayout(holder, animationInfo);ItemHolderInfo postInfo = mViewInfoStore.popFromPostLayout(holder);if (preInfo == null) {handleMissingPreInfoForChangeError(key, holder, oldChangeViewHolder);} else {animateChange(oldChangeViewHolder, holder, preInfo, postInfo,oldDisappearing, newDisappearing); // ②}}} else {mViewInfoStore.addToPostLayout(holder, animationInfo);}}// Step 4: Process view info lists and trigger animationsmViewInfoStore.process(mViewInfoProcessCallback);}// ...省略恢復初始設置的代碼}dispatchLayoutStep3()對ChildHelper中view進行遍歷,首先從view中獲取到holder,再根據holder的key,從ViewStoreInfo獲取3.3 dispatchLayoutStep1()步驟③中存入的oldChangeViewHolder,由于oldDisappearing為false且preInfo不為null,所以會調用animateChange(oldChangeViewHolder, holder, preInfo, postInfo, oldDisappearing, newDisappearing)方法。另外,需要注意的是,根據3.4的分析,如果是在notifyItemChanged(int position)調用導致的dispatchLayoutStep3()中,oldChangeViewHolder與holder不同;如果是在notifyItemChanged(int position, Object payload)調用導致的dispatchLayoutStep3()中,oldChangeViewHolder與holder相同。
接著看下animateChange()及其調用的相應方法。
可以看到如果oldHolder與newHolder相同,執行animateMove()方法,由于oldHolder與newHolder的位置相同,所以直接return了。而oldHolder與newHolder不同時,執行animateChange()方法,將newHolder 的view的alpha值設置為0。在動畫真正運行,即執行animateChangeImpl()方法時,newHolder的view會動畫顯示(alpha從0到1),oldHolder的view會動畫消失(alpha從1到0),這樣實現了CrossFade的效果,也就是出現了閃爍。
總結
以上是生活随笔為你收集整理的RecyclerView局部刷新和原理介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TBox、ECall、BCall、ICa
- 下一篇: 低频纹波、高频纹波、环路纹波、共模噪声、