概述
在日常開(kāi)發(fā)的過(guò)程中,同學(xué)們都遇到過(guò)需要RecyclerView
無(wú)限循環(huán)的需求谴麦,但是在官方提供的幾種LayoutManager
中并未支持無(wú)限循環(huán)捧书。
遇到此種問(wèn)題稼跳,通常的解決方案是:
1、在adapter
返回Integer.MAX_VALUE
并讓RecyclerView
滑動(dòng)到某個(gè)足夠大的位置阶剑。
2跃巡、選擇自定義LayoutManager
,實(shí)現(xiàn)循環(huán)的RecyclerView
牧愁。
自定義LayoutManager
的難度較高素邪,本文將帶大家一起實(shí)現(xiàn)這個(gè)自定義LayoutManager
,效果如下圖所示猪半。同時(shí)兔朦,在熟悉了在自定義LayoutManager
后,還可以根據(jù)需要調(diào)整RecyclerView
的展示效果磨确。
初探LayoutManager
自定義ViewGroup
類(lèi)似烘绽,自定義LayoutManager
所要做的就是ItemView
的「添加(add)」、「測(cè)量(measure)」俐填、「布局(layout)」安接。
但是自定義ViewGroup
相比,LayoutManager
多了一個(gè)「回收(recycle)」工作英融。
在自定義LayoutManager
之前盏檐,需要對(duì)其提供的「測(cè)量」、「布局」以及「回收」相關(guān)的API進(jìn)行了解驶悟。
measure
首先介紹測(cè)量方法胡野,與自定義ViewGroup類(lèi)似,測(cè)量通常是固定的邏輯不需要自己實(shí)現(xiàn)痕鳍,開(kāi)發(fā)者無(wú)需復(fù)寫(xiě)測(cè)量方法硫豆,只需要在布局之前調(diào)用測(cè)量函數(shù)來(lái)獲取將要布局的「View的寬度」即可。
LayoutManager
提供了兩個(gè)用來(lái)測(cè)量子View的方法:
//測(cè)量子View
public void measureChild(@NonNull View child, int widthUsed, int heightUsed)
//測(cè)量子View笼呆,并將子View的Margin也考慮進(jìn)來(lái)熊响,通常使用此函數(shù)
public void measureChildWithMargins(@NonNull View child, int widthUsed, int heightUsed)
測(cè)量完成后,便可以使用getMeasuredWidth()
、getMeasuredHeight()
直接獲取View的寬高诗赌,但是在自定義LayoutManager
中需要考慮ItemDecoration
汗茄,所以需要通過(guò)如下兩個(gè)API獲取測(cè)量后的View大小:
//獲取child的寬度,并將ItemDecoration考慮進(jìn)來(lái)
public int getDecoratedMeasuredWidth(@NonNull View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredWidth() + insets.left + insets.right;
}
//獲取child的高度铭若,并將ItemDecoration考慮進(jìn)來(lái)
public int getDecoratedMeasuredHeight(@NonNull View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredHeight() + insets.top + insets.bottom;
}
layout
然后介紹layout
方法洪碳,和自定義ViewGroup
一樣递览,LayoutManager
完成ItemView
的測(cè)量后就是布局了。
在LayoutManager
中瞳腌,并非靠直接調(diào)用ItemView的layout
函數(shù)進(jìn)行子View的布局绞铃,而是使用layoutDecorated
與layoutDecoratedWithMargins
, 兩者的區(qū)別是后者考慮了Margins:
public void layoutDecorated(@NonNull View child, int left, int top, int right, int bottom) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
child.layout(left + insets.left, top + insets.top, right - insets.right,
bottom - insets.bottom);
}
public void layoutDecoratedWithMargins(@NonNull View child, int left, int top, int right,
int bottom) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = lp.mDecorInsets;
child.layout(left + insets.left + lp.leftMargin, top + insets.top + lp.topMargin,
right - insets.right - lp.rightMargin,
bottom - insets.bottom - lp.bottomMargin);
}
recycle
回收是RecyclerView
的靈魂,也是RecyclerView
與普通ViewGroup
的區(qū)別嫂侍。眾所周知儿捧,RecyclerView中含有四類(lèi)緩存,在布局過(guò)程中它們各自有各自的用途:
1吵冒、AttachedScrap:
存放可見(jiàn)、不需要重新綁定的ViewHolder
2西剥、CachedViews
: 存放不可見(jiàn)痹栖、不需要重新綁定的ViewHoler
3、ViewCacheExtension
: 自定義緩存(存放不可見(jiàn)瞭空、不需要重新綁定)
4揪阿、RecyclerPool
: 存放不可見(jiàn)、需要重新綁定的ViewHolder
<div align="center">
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c9bd6e9d70b841699dbdd600e7c1fc1d~tplv-k3u1fbpfcp-watermark.image" width = "600" height = "400" alt="1xx"/>
</div>
在LayoutManager
中提供了多個(gè)回收方法:
//將指定的View直接回收加至ecyclerPool
public void removeAndRecycleView(@NonNull View child, @NonNull Recycler recycler) {
removeView(child);
recycler.recycleView(child);
}
//將指定位置的View直接回收加至ecyclerPool
public void removeAndRecycleViewAt(int index, @NonNull Recycler recycler) {
final View view = getChildAt(index);
removeViewAt(index);
recycler.recycleView(view);
}
LayoutManager創(chuàng)建
1咆畏、實(shí)現(xiàn)抽抽象方法南捂,并讓RecyclerView
可橫向滑動(dòng)
public class RepeatLayoutManager extends RecyclerView.LayoutManager {
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public boolean canScrollHorizontally() {
return true;
}
}
2、定義初始布局
在onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
方法中對(duì)ItemView
進(jìn)行添加旧找、測(cè)量溺健、布局。
具體步驟如下:
- 使用
recycler.getViewForPosition(int pos)
從緩存中獲取子View - 當(dāng)可布局區(qū)域有多余的空間時(shí),通過(guò)
addView(View view)
將對(duì)子View進(jìn)行添加钮蛛,通過(guò)在RecyclerView
中添加子View,并對(duì)子View進(jìn)行測(cè)量與布局鞭缭,直至子View超出RecyclerView
的可布局寬度。
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getItemCount() <= 0) {
return;
}
if (state.isPreLayout()) {
return;
}
//將所有Item分離至scrap
detachAndScrapAttachedViews(recycler);
int itemLeft = getPaddingLeft();
for (int i = 0; ; i++) {
if (itemLeft >= getWidth() - getPaddingRight()) {
break;
}
View itemView = recycler.getViewForPosition(i % getItemCount());
//添加子View
addView(itemView);
//測(cè)量子View
measureChildWithMargins(itemView, 0, 0);
int right = itemLeft + getDecoratedMeasuredWidth(itemView);
int top = getPaddingTop();
int bottom = top + getDecoratedMeasuredHeight(itemView) - getPaddingBottom();
//對(duì)子View進(jìn)行布局
layoutDecorated(itemView, itemLeft, top, right, bottom);
itemLeft = right;
}
}
3魏颓、滑動(dòng)與填充
offsetChildrenHorizontal(int x)
用作對(duì)RecyclerView
中的子View進(jìn)行整體左右移動(dòng)岭辣。
為了在滑動(dòng)RecyclerView
時(shí)有子View移動(dòng)的效果,需要復(fù)寫(xiě)scrollHorizontallyBy
函數(shù)甸饱,并在其中調(diào)用offsetChildrenHorizontal(int x)
沦童。
當(dāng)左滑后子View被左移動(dòng)時(shí),RecyclerView
的右側(cè)會(huì)出現(xiàn)可見(jiàn)的未填充區(qū)域叹话,這時(shí)需要在RecyclerView
右側(cè)添加并布局好新的子View偷遗,直到?jīng)]有可見(jiàn)的未填充區(qū)域?yàn)橹埂?br>
同樣,在右滑后需要對(duì)左側(cè)的未填充區(qū)域進(jìn)行填充驼壶。
具體代碼如下:
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
fill(recycler, dx > 0);
offsetChildrenHorizontal(-dx)鹦肿;
return dx;
}
/**
* 滑動(dòng)的時(shí)候,填充可見(jiàn)的未填充區(qū)域
*/
private void fill(RecyclerView.Recycler recycler, boolean fillEnd) {
if (getChildCount() == 0) return;
if (fillEnd) {
//填充尾部
View anchorView = getChildAt(getChildCount() - 1);
int anchorPosition = getPosition(anchorView);
for (; anchorView.getRight() < getWidth() - getPaddingRight(); ) {
int position = (anchorPosition + 1) % getItemCount();
if (position < 0) position += getItemCount();
View scrapItem = recycler.getViewForPosition(position);
addView(scrapItem);
measureChildWithMargins(scrapItem, 0, 0);
int left = anchorView.getRight();
int top = getPaddingTop();
int right = left + getDecoratedMeasuredWidth(scrapItem);
int bottom = top + getDecoratedMeasuredHeight(scrapItem) - getPaddingBottom();
layoutDecorated(scrapItem, left, top, right, bottom);
anchorView = scrapItem;
}
} else {
//填充首部
View anchorView = getChildAt(0);
int anchorPosition = getPosition(anchorView);
for (; anchorView.getLeft() > getPaddingLeft(); ) {
int position = (anchorPosition - 1) % getItemCount();
if (position < 0) position += getItemCount();
View scrapItem = recycler.getViewForPosition(position);
addView(scrapItem, 0);
measureChildWithMargins(scrapItem, 0, 0);
int right = anchorView.getLeft();
int top = getPaddingTop();
int left = right - getDecoratedMeasuredWidth(scrapItem);
int bottom = top + getDecoratedMeasuredHeight(scrapItem) - getPaddingBottom();
layoutDecorated(scrapItem, left, top,
right, bottom);
anchorView = scrapItem;
}
}
return;
}
回收
前面講到辅柴,當(dāng)對(duì)RecyclerView
進(jìn)行滑動(dòng)時(shí)箩溃,需要對(duì)可見(jiàn)的未填充區(qū)域進(jìn)行填充瞭吃。然而一直填充不做回收Item,那就和普通的ViewGroup
沒(méi)有太多的區(qū)別了涣旨。
在RecyclerView
中歪架,需要在滑動(dòng)、填充可見(jiàn)區(qū)域的同時(shí)霹陡,對(duì)不可見(jiàn)區(qū)域的子View進(jìn)行回收和蚪,這樣才能體現(xiàn)出RecyclerView
的優(yōu)勢(shì)。
回收的方向與填充的方向恰好相反烹棉。那回收的代碼具體如何實(shí)現(xiàn)呢攒霹?代碼如下:
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
fill(recycler, dx > 0);
offsetChildrenHorizontal(-dx);
recyclerChildView(dx > 0, recycler);
return dx;
}
/**
* 回收不可見(jiàn)的子View
*/
private void recyclerChildView(boolean fillEnd, RecyclerView.Recycler recycler) {
if (fillEnd) {
//回收頭部
for (int i = 0; ; i++) {
View view = getChildAt(i);
boolean needRecycler = view != null && view.getRight() < getPaddingLeft();
if (needRecycler) {
removeAndRecycleView(view, recycler);
} else {
return;
}
}
} else {
//回收尾部
for (int i = getChildCount() - 1; ; i--) {
View view = getChildAt(i);
boolean needRecycler = view != null && view.getLeft() > getWidth() - getPaddingRight();
if (needRecycler) {
removeAndRecycleView(view, recycler);
} else {
return;
}
}
}
}
使用
- 添加依賴
implementation 'cn.student0.manager:repeatmanager:1.0.2'
- 在代碼中使用
RecyclerView recyclerView = findViewById(R.id.rv_demo);
recyclerView.setAdapter(new DemoAdapter());
recyclerView.setLayoutManager(new RepeatLayoutManager
結(jié)語(yǔ)
到此,無(wú)限循環(huán)的LayoutManager
的實(shí)現(xiàn)已經(jīng)完成浆洗。文章的不足還請(qǐng)指出催束,謝謝大家。
Github地址:https://github.com/jiarWang/RepeatLayoutManager, 歡迎大家Star伏社。
感謝HenCoder團(tuán)隊(duì)
參考
Android自定義LayoutManager第十一式之飛龍?jiān)谔?/a>
【Android】掌握自定義LayoutManager(一) 系列開(kāi)篇 常見(jiàn)誤區(qū)抠刺、問(wèn)題、注意事項(xiàng)摘昌,常用API