原創(chuàng)內(nèi)容,轉(zhuǎn)載請(qǐng)注明出處:http://www.itdecent.cn/p/d774fa56dc1d
前言
上篇文章介紹了如何輕松實(shí)現(xiàn)RecyclerView添加分隔線,本文將延續(xù)之前的思路,研究如何實(shí)現(xiàn)網(wǎng)格分隔線的添加。首先我們要了解的是,網(wǎng)格分隔線相較線性更復(fù)雜一些,需要同時(shí)考慮行、列之間的繪制。一般實(shí)際項(xiàng)目中,網(wǎng)格列表只實(shí)現(xiàn)item之間添加分隔線,下面就針對(duì)這種情況開(kāi)始定義GridItemDecoration,目前支持設(shè)置行列間距大小、間距顏色,最后一行底部是否顯示,效果圖先走一發(fā):


如果你希望最后一行也顯示:

實(shí)現(xiàn)思路
繼承RecyclerView.ItemDecoration,重寫(xiě)
getItemOffsets(Rect outRect, View view, RecyclerView parent, State state)
onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)(或onDraw方法,兩者區(qū)別在于onDraw是在itemview繪制之前,onDrawOver是在itemview繪制之后),完整代碼如下:
/**
* 描述: 自定義網(wǎng)格ItemDecoration
* 作者: LemZ
*/
public class GridItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
private boolean mShowLastLine;
private int mHorizonSpan;
private int mVerticalSpan;
private GridItemDecoration(int horizonSpan,int verticalSpan,int color,boolean showLastLine) {
this.mHorizonSpan = horizonSpan;
this.mShowLastLine = showLastLine;
this.mVerticalSpan = verticalSpan;
mDivider = new ColorDrawable(color);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
drawHorizontal(c, parent);
drawVertical(c, parent);
}
private void drawHorizontal(Canvas c, RecyclerView parent) {
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
//最后一行底部橫線不繪制
if (isLastRaw(parent,i,getSpanCount(parent),childCount) && !mShowLastLine){
continue;
}
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getLeft() - params.leftMargin;
final int right = child.getRight() + params.rightMargin;
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mHorizonSpan;
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
private void drawVertical(Canvas c, RecyclerView parent) {
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if((parent.getChildViewHolder(child).getAdapterPosition() + 1) % getSpanCount(parent) == 0){
continue;
}
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getTop() - params.topMargin;
final int bottom = child.getBottom() + params.bottomMargin + mHorizonSpan;
final int left = child.getRight() + params.rightMargin;
int right = left + mVerticalSpan;
// //滿足條件( 最后一行 && 不繪制 ) 將vertical多出的一部分去掉;
if (i==childCount-1) {
right -= mVerticalSpan;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
/**
* 計(jì)算偏移量
* */
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int spanCount = getSpanCount(parent);
int childCount = parent.getAdapter().getItemCount();
int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
if (itemPosition < 0){
return;
}
int column = itemPosition % spanCount;
int bottom;
int left = column * mVerticalSpan / spanCount;
int right = mVerticalSpan - (column + 1) * mVerticalSpan / spanCount;
if (isLastRaw(parent, itemPosition, spanCount, childCount)){
if (mShowLastLine){
bottom = mHorizonSpan;
}else{
bottom = 0;
}
}else{
bottom = mHorizonSpan;
}
outRect.set(left, 0, right, bottom);
}
/**
* 獲取列數(shù)
* */
private int getSpanCount(RecyclerView parent) {
// 列數(shù)
int mSpanCount = -1;
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
mSpanCount = ((GridLayoutManager) layoutManager).getSpanCount();
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
mSpanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
}
return mSpanCount;
}
/**
* 是否最后一行
* @param parent RecyclerView
* @param pos 當(dāng)前item的位置
* @param spanCount 每行顯示的item個(gè)數(shù)
* @param childCount child個(gè)數(shù)
* */
private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) {
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
return getResult(pos,spanCount,childCount);
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
if (orientation == StaggeredGridLayoutManager.VERTICAL) {
// StaggeredGridLayoutManager 且縱向滾動(dòng)
return getResult(pos,spanCount,childCount);
} else {
// StaggeredGridLayoutManager 且橫向滾動(dòng)
if ((pos + 1) % spanCount == 0) {
return true;
}
}
}
return false;
}
private boolean getResult(int pos,int spanCount,int childCount){
int remainCount = childCount % spanCount;//獲取余數(shù)
//如果正好最后一行完整;
if (remainCount == 0){
if(pos >= childCount - spanCount){
return true; //最后一行全部不繪制;
}
}else{
if (pos >= childCount - childCount % spanCount){
return true;
}
}
return false;
}
/**
* 使用Builder構(gòu)造
* */
public static class Builder {
private Context mContext;
private Resources mResources;
private boolean mShowLastLine;
private int mHorizonSpan;
private int mVerticalSpan;
private int mColor;
public Builder(Context context) {
mContext = context;
mResources = context.getResources();
mShowLastLine = true;
mHorizonSpan = 0;
mVerticalSpan = 0;
mColor = Color.WHITE;
}
/**
* 通過(guò)資源文件設(shè)置分隔線顏色
*/
public Builder setColorResource(@ColorRes int resource) {
setColor(ContextCompat.getColor(mContext, resource));
return this;
}
/**
* 設(shè)置顏色
*/
public Builder setColor(@ColorInt int color) {
mColor = color;
return this;
}
/**
* 通過(guò)dp設(shè)置垂直間距
* */
public Builder setVerticalSpan(@DimenRes int vertical) {
this.mVerticalSpan = mResources.getDimensionPixelSize(vertical);
return this;
}
/**
* 通過(guò)px設(shè)置垂直間距
* */
public Builder setVerticalSpan(float mVertical) {
this.mVerticalSpan = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mVertical, mResources.getDisplayMetrics());
return this;
}
/**
* 通過(guò)dp設(shè)置水平間距
* */
public Builder setHorizontalSpan(@DimenRes int horizontal) {
this.mHorizonSpan = mResources.getDimensionPixelSize(horizontal);
return this;
}
/**
* 通過(guò)px設(shè)置水平間距
* */
public Builder setHorizontalSpan(float horizontal) {
this.mHorizonSpan = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, horizontal, mResources.getDisplayMetrics());
return this;
}
/**
* 是否最后一條顯示分割線
* */
public GridItemDecoration.Builder setShowLastLine(boolean show){
mShowLastLine = show;
return this;
}
public GridItemDecoration build() {
return new GridItemDecoration(mHorizonSpan, mVerticalSpan, mColor,mShowLastLine);
}
}
}
繪制行之間橫線,drawHorizontal()需添加判斷最后一行是否需繪制
//最后一行底部橫線不繪制
if (isLastRaw(parent,i,getSpanCount(parent),childCount) && !mShowLastLine){
continue;
}
繪制列之間豎線時(shí),若網(wǎng)格未占滿一行,顯示出來(lái)的最后一個(gè)item右側(cè)會(huì)繪制分隔,不需要的話應(yīng)添加判斷
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getTop() - params.topMargin;
final int bottom = child.getBottom() + params.bottomMargin + mHorizonSpan;
final int left = child.getRight() + params.rightMargin;
int right = left + mVerticalSpan;
// //滿足條件( 最后一行 && 不繪制 ) 將vertical多出的一部分去掉;
if (i==childCount-1) {
right -= mVerticalSpan;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
,需要繪制則注釋,在網(wǎng)格列表中如果最后一行正好擺滿,(如總9個(gè), 3列) 最后一行還是會(huì)顯示,必須添加getResult方法,完善判斷,代碼量不是很多,主要就是一些判斷的注意,具體測(cè)量可以詳細(xì)閱讀不難理解。
通過(guò)builder設(shè)置你想要的效果,包括顏色、間距等,具體使用代碼如下:
GridLayoutManager gridLayoutManager = new GridLayoutManager(context,3);
GridItemDecoration divider = new GridItemDecoration.Builder(context)
.setHorizontalSpan(R.dimen.common_vew_column_padding)
.setVerticalSpan(R.dimen.common_vew_raw_padding)
.setColorResource(R.color.orange)
.setShowLastLine(true)
.build();
recycle_recommend.addItemDecoration(divider);
recycle_recommend.setLayoutManager(gridLayoutManager);
結(jié)尾
目前該自定義GridItemDecoration能滿足大部分需求,若需要四周繪制可以在此基礎(chǔ)上重新計(jì)算偏移量及繪制間距,橫豎方向間隔顯示不同顏色也可以添加drawable對(duì)象或設(shè)置不同paint實(shí)現(xiàn),有時(shí)間我也會(huì)再擴(kuò)展一下^ ^