很多文章上来就直接点明RecyclerView的复用从何开始,对于一般开发者应该是一脸懵逼的开始,一脸懵逼的结束,本文章告诉你,如何自己分析RecyclerView的复用机制。
从什么是RecyclerView开始
这个问题复杂也不复杂,我们一般会把RecyclerView与ListView做对比,更多的是拿RecyclerView的优势与ListView做对比,其实这并没有什么意义,因为RecyclerView的诞生就是要实现一个高度封装的ListView(并不是ListView)。谷歌也建议我们的列表用RecyclerView来实现,可见RecyclerView的地位是相当高的。
什么是RecyclerView的复用机制
首先,RecyclerView的一般用法是这样:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = RecyclerViewAdapter(this@MainActivity)
}
}
class RecyclerViewAdapter(private val mContext: Context) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext)
.inflate(R.layout.recyclerview_layout_item, parent, false)
d("onCreateViewHolder: viewType = $viewType")
return ViewHolder(view)
}
override fun getItemCount(): Int {
return 200
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
d("onBindViewHolder: position= $position")
}
class ViewHolder(item: View):RecyclerView.ViewHolder(item){}
}
列表子布局很简单,就一个TextView。为了直观,没有写的很复杂。我们运行起来,
在列表展示出来后可以看到log输出
2020-07-07 10:54:35.433 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.436 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 0
2020-07-07 10:54:35.454 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.454 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 1
2020-07-07 10:54:35.467 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.468 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 2
2020-07-07 10:54:35.480 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.480 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 3
2020-07-07 10:54:35.492 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.492 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 4
2020-07-07 10:54:35.505 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.506 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 5
2020-07-07 10:54:35.518 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.518 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 6
2020-07-07 10:54:35.531 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:54:35.532 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 7
onCreateViewHoldler方法与onBindViewHodler方法都被调用了。手指滑动一下,log如下:
2020-07-07 10:56:50.379 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:56:50.379 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 8
2020-07-07 10:56:50.401 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:56:50.401 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 9
2020-07-07 10:56:50.453 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:56:50.453 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 10
2020-07-07 10:56:50.487 25655-25655/com.dxs.universityofsound D/dxs: onCreateViewHolder: viewType = 0
2020-07-07 10:56:50.487 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 11
2020-07-07 10:56:50.504 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 12
2020-07-07 10:56:50.535 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 13
2020-07-07 10:56:50.585 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 14
2020-07-07 10:56:50.617 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 15
2020-07-07 10:56:50.665 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 16
2020-07-07 10:56:50.718 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 17
2020-07-07 10:56:50.768 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 18
2020-07-07 10:56:50.835 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 19
2020-07-07 10:56:50.919 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 20
2020-07-07 10:56:51.035 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 21
2020-07-07 10:56:51.184 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 22
2020-07-07 10:56:51.550 25655-25655/com.dxs.universityofsound D/dxs: onBindViewHolder: position= 23
注意,在onCreateViewhodler调用四次后,就不再调用了,也就是说,ViewHodler不再创建了。这就是复用机制的功劳,在列表展示的时候,不用过多的创建ViewHodler,当ViewHolder可复用的时候,直接使用复用的ViewHodler。
如何开始?
了解了什么是复用,那么它是怎么实现的,我们应该如何开始分析它的原理呢?
首先我们应该考虑一个问题,是什么样的情况会触发复用呢?
我们可以看到,在滑动的时候,复用机制触发了。
再者就是界面重新布局的时候(其实也算是滑动啦!)。
寻找入口
既然是滑动,那离不开的方法是onTouchEvent,进入RecyclerView的onTouchEvent方法中。从哪个事件开始,这就很明白了,直接看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;
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[1] = 0;
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)) {
getParent().requestDisallowInterceptTouchEvent(true);
}
if (mGapWorker != null && (dx != 0 || dy != 0)) {
mGapWorker.postFromTraversal(this, dx, dy);
}
很明显dispatchNestedPreScroll()是嵌套滑动使用的。那么只可能是scrollByInternal()方法了
在scrollByInternal()方法中,可以很容易定位到scrollStep()方法,继续跟下去
boolean scrollByInternal(int x, int y, MotionEvent ev) {
consumePendingUpdateOperations();
if (mAdapter != null) {
mReusableIntPair[0] = 0;
mReusableIntPair[1] = 0;
scrollStep(x, y, mReusableIntPair);
consumedX = mReusableIntPair[0];
consumedY = mReusableIntPair[1];
unconsumedX = x - consumedX;
unconsumedY = y - consumedY;
}
.........
}
void scrollStep(int dx, int dy, @Nullable int[] consumed) {
int consumedX = 0;
int consumedY = 0;
if (dx != 0) {
consumedX = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
}
if (dy != 0) {
consumedY = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
}
}
mLayout是什么,它就是LayoutManager,这是一个抽象类,我们使用的LayoutManager是LinearLayoutManager(其实GridLayoutManager也是继承自LinearLayoutManager),因为我们是竖向滑动那么就直接到LinearLayoutManager中的scrollVerticallyBy()方法,一直跟到ScrollBy()方法
int scrollBy(int delta, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0 || delta == 0) {
return 0;
}
ensureLayoutState();
mLayoutState.mRecycle = true;
final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
final int absDelta = Math.abs(delta);
updateLayoutState(layoutDirection, absDelta, true, state);
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;
}
可以看到传入的参数中,RecyclerView.Recycler很明显了,这就是缓存类了。里面的内容就不具体分析了,有兴趣的朋友自己看下吧。可以看到recycler传入了fill()方法中,在fill()方法中,将recycler传入layoutChunk()方法中,在layoutChunk方法中调用了layoutState的next()方法继续跟进。
View next(RecyclerView.Recycler recycler) {
if (mScrapList != null) {
return nextViewFromScrapList();
}
final View view = recycler.getViewForPosition(mCurrentPosition);
mCurrentPosition += mItemDirection;
return view;
}
调用了Recycler的getViewForPosition方法,这是很多文章中说的入口,也是从这里,复用机制的源码才开始了。
到这里,我们算是从滑动角度找到了复用机制的源码。那么从另外一个角度呢?
我们知道,所有的View在布局的时候必须经历的方法onLayout(),找到RecyclerView的onLayout()方法。因为方法较短直接进入dispatchlayout。
void dispatchLayout() {
if (mAdapter == null) {
Log.e(TAG, "No adapter attached; skipping layout");
// leave the state in START
return;
}
if (mLayout == null) {
Log.e(TAG, "No layout manager attached; skipping layout");
// leave the state in START
return;
}
mState.mIsMeasuring = false;
if (mState.mLayoutStep == State.STEP_START) {
dispatchLayoutStep1();
mLayout.setExactMeasureSpecsFrom(this);
dispatchLayoutStep2();
} else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth()
|| mLayout.getHeight() != getHeight()) {
// First 2 steps are done in onMeasure but looks like we have to run again due to
// changed size.
mLayout.setExactMeasureSpecsFrom(this);
dispatchLayoutStep2();
} else {
// always make sure we sync them (to ensure mode is exact)
mLayout.setExactMeasureSpecsFrom(this);
}
dispatchLayoutStep3();
}
我们找两个关键1、Recycler 2、layoutmanager
因为版本问题我这里的代码是2020年最新的,在6.0的时候这里只有一步。我们直接进入第二步
在里面看到onLayoutChildren()方法进入LinearLayoutManager中看此方法,最终还是会执行到fill()方法
值得一提的是,在layoutChunk()方法中,addView()可以知道,RecyclerView也是通过这样的方法添加跟移除View的。了解了本质,我们看一看这个View是如何处理的。
复用机制
RecyclerView的复用机制分为四级(每个人分法不一样,不需要太执着这个)
- mAttachedScrap and mChangedScrap
- mCachedViews
- mViewCacheExtension
- mRecyclerPool
至于他们之间是如何运作的。我们继续fuck源码。
跟随getViewForPosition()方法找到tryGetViewHolderForPositionByDeadline()这个方法名称取的很明了了。“尝试按截止日期获取位置的视图持有人”
篇幅问题,我就不把整段代码粘上来了。只说一下最重要的几个方法。
在这个方法中,唯一的主题即为:ViewHolder在哪里。
第一个方法:getChangedScrapViewForPosition()
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 position
for (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;
}
}
// find by id
if (mAdapter.hasStableIds()) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) {
final long id = mAdapter.getItemId(offsetPosition);
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
}
}
return null;
}
这个方法中通过Position与Id在mChangedScrap中查找ViewHodler。
接下来getScrapOrHiddenOrCachedHolderForPosition()
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;
}
}
........
// 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 getScrapOrCachedViewForId
if (!holder.isInvalid() && holder.getLayoutPosition() == position
&& !holder.isAttachedToTransitionOverlay()) {
if (!dryRun) {
mCachedViews.remove(i);
}
if (DEBUG) {
Log.d(TAG, "getScrapOrHiddenOrCachedHolderForPosition(" + position
+ ") found match in cache: " + holder);
}
return holder;
}
}
}
通过遍历mAttachedScrap获取ViewHolder
接着遍历mCachedViews获取ViewHolder
接下来从mViewCacheExtension获取
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());
}
}
}
最后通过mRecyclerPool获取
if (holder == null) { // fallback to pool
if (DEBUG) {
Log.d(TAG, "tryGetViewHolderForPositionByDeadline("
+ position + ") fetching from shared pool");
}
holder = getRecycledViewPool().getRecycledView(type);
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
以上就是复用机制中,读取viewholder的源码分析,深入点可以研究各个容器中存储规则。不想继续写了~