Android L面世之后,Google就推薦在開發項目中使用RecyclerView來取代ListView,因為RecyclerView的靈活性跟性能都要比ListView更強,但是,帶來的問題也不少,比如:列表分割線都要開發者自己控制,再者,RecyclerView的測量與布局的邏輯都委托給了自己LayoutManager來處理,如果需要對RecyclerView進行改造,相應的也要對其LayoutManager進行定制。本文主要就以以下場景給出RecyclerView使用參考:
RecyclerView的幾種常用場景
- 如何實現帶分割線的列表式RecyclerView
- 如何實現帶分割線網格式RecyclerView
- 如何實現全展開的列表式RecyclerView(比如:嵌套到ScrollView中使用)
- 如何實現全展開的網格式RecyclerView(比如:嵌套到ScrollView中使用)
先看一下實現樣式,為了方便控制,邊界的均不設置分割線,方便定制,如果需要可以采用Padding或者Margin來實現。Github連接 RecyclerItemDecoration
不同場景RecyclerView實現
默認的縱向列表式RecyclerView
首先看一下最簡單的縱向線性RecyclerView,一般用以下代碼:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
以上就是最簡單的線性RecyclerView的實現,但默認不帶分割線,如果想要使用比如20dp的黑色作為分割線,就需要自己定制,Google為RecyclerView提供了ItemDecoration,它的作用就是為Item添加一些附屬信息,比如:分割線,浮層等。
帶分割線的列表式RecyclerView--LinearItemDecoration
RecyclerView提供了addItemDecoration接口與ItemDecoration類用來定制分割線樣式,那么,在RecyclerView源碼中,是怎么用使用ItemDecoration的呢。與普通View的繪制流程一致,RecyclerView也要經過measure->layout->draw,并且在measure、layout之后,就應該按照ItemDecoration的限制,為RecyclerView的分割線挪出空間。RecyclerView的measure跟Layout其實都是委托給自己的LayoutManager的,在LinearLayoutManager測量或者布局時都會直接或者間接調用RecyclerView的measureChildWithMargins函數,而measureChildWithMargins函數會進一步找到addItemDecoration添加的ItemDecoration,通過其getItemOffsets函數獲取所需空間信息,源碼如下:
public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
getPaddingLeft() + getPaddingRight() +
lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
getPaddingTop() + getPaddingBottom() +
lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
canScrollVertically());
if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
child.measure(widthSpec, heightSpec);
}
}
可見measureChildWithMargins會首先通過getItemDecorInsetsForChild計算出每個child的ItemDecoration所限制的邊界信息,之后將邊界所需的空間作為已用空間為child構造MeasureSpec,最后用MeasureSpec對child進行尺寸測量:child.measure(widthSpec, heightSpec);來看一下getItemDecorInsetsForChild函數:
Rect getItemDecorInsetsForChild(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.mInsetsDirty) {
return lp.mDecorInsets;
}
final Rect insets = lp.mDecorInsets;
insets.set(0, 0, 0, 0);
final int decorCount = mItemDecorations.size();
for (int i = 0; i < decorCount; i++) {
mTempRect.set(0, 0, 0, 0);
<!--通過這里知道,需要繪制的空間位置-->
mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
insets.left += mTempRect.left;
insets.top += mTempRect.top;
insets.right += mTempRect.right;
insets.bottom += mTempRect.bottom;
}
lp.mInsetsDirty = false;
return insets;
}
一般而言,不會同時設置多類ItemDecoration,太麻煩,對于普通的線性布局列表,其實就簡單設定一個自定義ItemDecoration即可,其中outRect參數主要是控制每個Item上下左右的分割線所占據的寬度跟高度,這個尺寸跟繪制的時候的尺寸應該對應(如果需要繪制的話),看一下LinearItemDecoration的getItemOffsets實現:
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
<!--垂直方向 ,最后一個不設置padding-->
if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount()1) {
outRect.set(0, 0, 0, mSpanSpace);
} else {
outRect.set(0, 0, 0, 0);
}
} else {
<!--水平方向 ,最后一個不設置padding-->
if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount()1) {
outRect.set(0, 0, mSpanSpace, 0);
} else {
outRect.set(0, 0, 0, 0);
}
}
}
measure跟layout之后,再來看一下RecyclerView的onDraw函數, RecyclerView在onDraw函數中會調用ItemDecoration的onDraw,繪制分割線或者其他輔助信息,ItemDecoration 支持上下左右四個方向定制占位分割線等信息,具體要繪制的樣式跟位置都完全由開發者確定,所以自由度非常大,其實如果不是太特殊的需求的話,onDraw函數完全可以不做任何處理,僅僅用背景色就可以達到簡單的分割線的目的,當然,如果想要定制一些特殊的圖案之類的需話,就需要自己繪制,來看一下LinearItemDecoration的onDraw(只看Vertical的)
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
...
}
}
其實,如果不是特殊的繪制需求,比如顯示七彩的,或者圖片,完全不需要任何繪制,如果一定要繪制,注意繪制的尺寸區域跟原來getItemOffsets所限制的區域一致,繪制的區域過大不僅不會顯示出來,還會引起過度繪制的問題:
public void drawVertical(Canvas c, RecyclerView parent) { int totalCount = parent.getAdapter().getItemCount(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child)); final int bottom = top + mVerticalSpan; final int left = child.getLeft() + params.leftMargin; final int right = child.getRight() + params.rightMargin; if (!isLastRaw(parent, i, mSpanCount, totalCount)) if (childCounti > mSpanCount) { drawable.setBounds(left, top, right, bottom); drawable.draw(c); }
}
}
帶分割線的網格式RecyclerView--GridLayoutItemDecoration
網格式RecyclerView的處理流程跟上面的線性列表類似,不過網格式的需要根據每個Item的位置為其設置好邊距,比如最左面的不需要左邊占位,最右面的不需要右面的占位,最后一行不需要底部的占位,如下圖所示
RecyclerView的每個childView都會通過getItemOffsets來設置自己ItemDecoration,對于網格式的RecyclerView,需要在四個方向上對其ItemDecoration進行限制,來看一下其實現類GridLayoutItemDecoration的getItemOffsets:
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final int position = parent.getChildAdapterPosition(view);
final int totalCount = parent.getAdapter().getItemCount();
int left = (position % mSpanCount == 0) ? 0 : mHorizonSpan;
int bottom = ((position + 1) % mSpanCount == 0) ? 0 : mVerticalSpan;
if (isVertical(parent)) {
if (!isLastRaw(parent, position, mSpanCount, totalCount)) {
outRect.set(left, 0, 0, mVerticalSpan);
} else {
outRect.set(left, 0, 0, 0);
}
} else {
if (!isLastColumn(parent, position, mSpanCount, totalCount)) {
outRect.set(0, 0, mHorizonSpan, bottom);
} else {
outRect.set(0, 0, 0, bottom);
}
}
}
其實上面的代碼就是根據RecyclerView滑動方向(橫向或者縱向)以及child的位置(是不是最后一行或者最后一列),對附屬區域進行限制,同樣,如果不是特殊的分割線樣式,通過背景就基本可以實現需求,不用特殊draw。
全展開的列表式RecyclerView--ExpandedLinearLayoutManager
RecyclerView全展開的邏輯跟分割線不同,全展開主要是跟measure邏輯相關,簡單看一下RecyclerView(v-22版本,相對簡單)的measure源碼:
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
...
<!--關鍵代碼,如果mLayout(LayoutManager)非空,就采用LayoutManager的mLayout.onMeasure-->
if (mLayout == null) {
defaultOnMeasure(widthSpec, heightSpec);
} else {
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
}
mState.mInPreLayout = false; // clear
}
由以上代碼可以看出,在為RecyclerView設置了LayoutManager之后,RecyclerView的measure邏輯其實就是委托給了它的LayoutManager,這里以LinearLayoutManager為例,不過LinearLayoutManager源碼里面并沒有重寫onMeasure函數,也就是說,對于RecyclerView的線性樣式,對于尺寸的處理采用的是跟ViewGroup一樣的處理,完全由父控件限制,不過對于v-23里面有了一些修改,就是增加了對wrap_content的支持。既然這樣,我們就可以把設置尺寸的時機放到LayoutManager的onMeasure中,對全展開的RecyclerView來說,其實就是將所有child測量一遍,之后將每個child需要高度或者寬度累加,看一下ExpandedLinearLayoutManager的實現:在測量child的時候,采用RecyclerView的measureChildWithMargins,該函數已經將ItemDecoration的占位考慮進去,之后通過getDecoratedMeasuredWidth獲取真正需要占用的尺寸。
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int measureWidth = 0;
int measureHeight = 0;
int count;
if (mMaxItemCount < 0 || getItemCount() < mMaxItemCount) {
count = getItemCount();
} else {
count = mMaxItemCount;
}
for (int i = 0; i < count; i++) {
int[] measuredDimension = getChildDimension(recycler, i);
if (measuredDimension == null || measuredDimension.length != 2)
return;
if (getOrientation() == HORIZONTAL) {
measureWidth = measureWidth + measuredDimension[0];
<!--獲取最大高度-->
measureHeight = Math.max(measureHeight, measuredDimension[1]);
} else {
measureHeight = measureHeight + measuredDimension[1];
<!--獲取最大寬度-->
measureWidth = Math.max(measureWidth, measuredDimension[0]);
}
}
measureHeight = heightMode == View.MeasureSpec.EXACTLY ? heightSize : measureHeight;
measureWidth = widthMode == View.MeasureSpec.EXACTLY ? widthSize : measureWidth;
if (getOrientation() == VERTICAL && measureWidth > widthSize) {
measureWidth = widthSize;
} else if (getOrientation() == HORIZONTAL && measureHeight > heightSize) {
measureHeight = heightSize;
}
setMeasuredDimension(measureWidth, measureHeight);
}
private int[] getChildDimension(RecyclerView.Recycler recycler, int position) {
try {
int[] measuredDimension = new int[2];
View view = recycler.getViewForPosition(position);
//測量childView,以便獲得寬高(包括ItemDecoration的限制)
super.measureChildWithMargins(view, 0, 0);
//獲取childView,以便獲得寬高(包括ItemDecoration的限制),以及邊距
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
return measuredDimension;
} catch (Exception e) {
Log.d("LayoutManager", e.toString());
}
return null;
}
全展開的網格式RecyclerView--ExpandedGridLayoutManager
全展開的網格式RecyclerView的實現跟線性的十分相似,唯一不同的就是在確定尺寸的時候,不是將每個child的尺寸疊加,而是要將每一行或者每一列的尺寸疊加,這里假定行高或者列寬都是相同的,其實在使用中這兩種場景也是最常見的,看如下代碼,其實除了加了行與列判斷邏輯,其他基本跟上面的全展開線性的類似。
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int measureWidth = 0;
int measureHeight = 0;
int count = getItemCount();
int span = getSpanCount();
for (int i = 0; i < count; i++) {
measuredDimension = getChildDimension(recycler, i);
if (getOrientation() == HORIZONTAL) {
if (i % span == 0 ) {
measureWidth = measureWidth + measuredDimension[0];
}
measureHeight = Math.max(measureHeight, measuredDimension[1]);
} else {
if (i % span == 0) {
measureHeight = measureHeight + measuredDimension[1];
}
measureWidth = Math.max(measureWidth, measuredDimension[0]);
}
}
measureHeight = heightMode == View.MeasureSpec.EXACTLY ? heightSize : measureHeight;
measureWidth = widthMode == View.MeasureSpec.EXACTLY ? widthSize : measureWidth;
setMeasuredDimension(measureWidth, measureHeight);
}
最后附上橫向滑動效果圖:
以上就是比較通用的RecyclerView使用場景及所做的兼容 ,最后附上Github鏈接RecyclerItemDecoration,歡迎star,fork。
作者:看書的小蝸牛
原文鏈接: RecyclerView定制:通用ItemDecoration及全展開RecyclerView的實現