RecyclerView定制:通用ItemDecoration及全展开RecyclerView的实现

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的位置为其设置好边距,比如最左面的不需要左边占位,最右面的不需要右面的占位,最后一行不需要底部的占位,如下图所示

网格式ItemDocration的限制

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的实现

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容