RecyclerView addItemDecoration 的妙用 - item 间距平均分布和添加分割线

3,479 阅读8分钟

前言

RecyclerView,在开发当中使用非常频繁的一个控件,今天,主要讲解以下两个问题

  • 添加分割线

  • item 间距的平均分布


addItemDecoration 方法简介

我们先来看一下 addItemDecoration 方法

官网链接

Add an RecyclerView.ItemDecoration to this RecyclerView. Item decorations can affect both measurement and drawing of individual item views.

Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.

简单来来说,ItemDecoration 是 itemView 的装饰,可以影响 itemView 的 measurement 和 draw。

ItemDecoration 主要有几个方法

getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)

Retrieve any offsets for the given item. Each field of outRect specifies the number of pixels that the item view should be inset by, similar to padding or margin. The default implementation sets the bounds of outRect to 0 and returns.

可以影响 item 的大小,类似于在 item 中设置 padding 和 margin。

void onDraw (Canvas c, RecyclerView parent, RecyclerView.State state)

Draw any appropriate decorations into the Canvas supplied to the RecyclerView. Any content drawn by this method will be drawn before the item views are drawn, and will thus appear underneath the views.

在 itemView 之前绘制

void onDrawOver (Canvas c, RecyclerView parent, RecyclerView.State state)

Draw any appropriate decorations into the Canvas supplied to the RecyclerView. Any content drawn by this method will be drawn after the item views are drawn and will thus appear over the views.

在 itemView 之后绘制


添加分割线

效果图如下

RecyclerViewDivider,已支持以下功能

  1. 自定义分割线,设置 drawable

  2. 设置分割线高度,颜色

  3. 设置分割线距离屏幕左边,右边的距离

  4. 设置是否显示最后一条分割线

详情代码见 RecyclerViewSample

实现思路

我们知道 RecyclerView 没有像之前 ListView 提供 divider 属性,设置分割线的话有挺多人在 itemView 的布局里面加个 1dp 左右的 view,根据业务场景设置是否可见。这是其中的一种方法,但其实,我们也可以使用 recyclerView.addItemDecoration() 来实现,主要需要重写 getItemOffsets 和 onDraw 方法

思路很简单

  1. 重写 getItemOffsets,加上 divider 的高度,影响 itemView 的最终 size

  2. 在 onDraw 方法,根据 LinearLayoutManager 的方向分别绘制分割线

 1@Override 2public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { 3    super.getItemOffsets(outRect, view, parent, state); 4    outRect.set(0, 0, 0, mDividerHeight); 5} 6 7@Override 8public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 9    super.onDraw(c, parent, state);10    if (mOrientation == LinearLayoutManager.VERTICAL) {11        drawVerticalDivider(c, parent);12    } else {13        drawHorizontalDivider(c, parent);14    }15}
 1//Draw item dividing line 2private void drawVerticalDivider(Canvas canvas, RecyclerView parent) { 3    // mLeftOffset 为自己设置的左边偏移量 4    final int left = parent.getPaddingLeft() + mLeftOffset; 5    // mRightOffset 为设置的右边偏移量 6    final int right = parent.getMeasuredWidth() - parent.getPaddingRight() + mRightOffset; 7    final int childSize = parent.getChildCount(); 8 9    if (childSize <= 0) {10        return;11    }1213    // 从第一个 item 开始绘制14    int first = mStart;15    // 到第几个 item 绘制结束16    int last = childSize - mEnd - (mIsShowLastDivider ? 0 : 1);17    Log.d(TAG, " last = " + last + " childSize =" + childSize + "left = " + left);1819    if (last <= 0) {20        return;21    }2223    for (int i = first; i < last; i++) {24        drawableVerticalDivider(canvas, parent, left, right, i, mDividerHeight);25    }2627}2829private void drawableVerticalDivider(Canvas canvas, RecyclerView parent, int left, int right, int i, int dividerHeight) {30    final View child = parent.getChildAt(i);3132    if (child == null) {33        return;34    }3536    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();37    final int top = child.getBottom() + layoutParams.bottomMargin;38    final int bottom = top + dividerHeight;3940    // 适配 drawable41    if (mDivider != null) {42        mDivider.setBounds(left, top, right, bottom);43        mDivider.draw(canvas);44    }4546    // 适配分割线47    if (mPaint != null) {48        canvas.drawRect(left, top, right, bottom, mPaint);49    }50}

Item 间距平均分布

针对 GridLayoutManager 的

在 Android 开发当中,我们经常会看到这样的界面,

一般来说,可能有以下几种需求:

  1. 要求第一列和最后一列距离屏幕的距离 A 是固定的,其余每个 item 之间的距离 B 也是固定的(但 A 不等于 B

  2. 要求第一列和最后一列距离屏幕的距离 A 是固定的,item 的大小是固定的,其余每个 item 之间的距离跟随分辨率的大小变化

  3. 第一行距离顶部的距离可以设置,最后一行距离底部的距离可以设置

思路分析

首先,我们知道,对于 GridLayoutmanager ,当我们设置的 spancount 为 3 的时候,那么每个 item的最大宽度为 itemMaxW = recycylerW / spancount = recycylerW / 3.

假设我们 spancount 为 3,那么在不设置 itemDercation 的情况下它的分布是这样的,可以看到第一列与最后一行的距离是不一样的

而加上 itemDercation 之后,我们所看到的 item 是这样的,因此,我们可以分别对每个 item 的 ouctRect 进行处理

核心代码如下:

 1@Override 2public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { 3    super.getItemOffsets(outRect, view, parent, state); 4 5    int top = 0; 6    int left; 7    int right; 8    int bottom; 910    int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();11    mSpanCount = getSpanCount(parent);12    int childCount = parent.getAdapter().getItemCount();1314    // 屏幕宽度-View的宽度*spanCount 得到屏幕剩余空间15    int maxDividerWidth = getMaxDividerWidth(view);16    int spaceWidth = mFirstAndLastColumnW;//首尾两列与父布局之间的间隔17    // 除去首尾两列,item与item之间的距离18    int eachItemWidth = maxDividerWidth / mSpanCount;19    int dividerItemWidth = (maxDividerWidth - 2 * spaceWidth) / (mSpanCount - 1);//item与item之间的距离2021    left = itemPosition % mSpanCount * (dividerItemWidth - eachItemWidth) + spaceWidth;22    right = eachItemWidth - left;23    bottom = dividerItemWidth;2425    // 首行26    if (mFirstRowTopMargin > 0 && isFirstRow(parent, itemPosition, mSpanCount, childCount)) {27        top = mFirstRowTopMargin;28    }2930    //最后一行31    if (isLastRow(parent, itemPosition, mSpanCount, childCount)) {32        if (mLastRowBottomMargin < 0) {33            bottom = 0;34        } else {35            bottom = mLastRowBottomMargin;36        }37    }3839    Log.i(TAG, "getItemOffsets: dividerItemWidth =" + dividerItemWidth + "eachItemWidth = " + eachItemWidth);4041    Log.i(TAG, "getItemOffsets: itemPosition =" + itemPosition + " left = " + left + " top = " + top42            + " right = " + right + " bottom = " + bottom);4344    outRect.set(left, top, right, bottom);45}

在代码中使用

 1mRecyclerView.setLayoutManager(layoutManager); 2int firstAndLastColumnW = DisplayUtils.dp2px(this, 15); 3int firstRowTopMargin = DisplayUtils.dp2px(this, 15); 4GridDividerItemDecoration gridDividerItemDecoration = 5        new GridDividerItemDecoration(this, firstAndLastColumnW, firstRowTopMargin, firstRowTopMargin); 6gridDividerItemDecoration.setFirstRowTopMargin(firstRowTopMargin); 7gridDividerItemDecoration.setLastRowBottomMargin(firstRowTopMargin); 8mRecyclerView.addItemDecoration(gridDividerItemDecoration); 9List<Integer> imageList = DataUtils.produceImageList(30);10ImageAdapter imageAdapter = new ImageAdapter(this, imageList);1112mRecyclerView.setAdapter(imageAdapter);

针对横向的 LinearlayoutManager

 1@Override 2public void getItemOffsets(Rect outRect, View view, 3                           RecyclerView parent, RecyclerView.State state) { 4    int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); 5    int childCount = parent.getAdapter().getItemCount(); 6 7    if (itemPosition == 0) { 8        outRect.left = firstAndlastRect.left; 9        outRect.right = firstAndlastRect.right;10        outRect.bottom = firstAndlastRect.bottom;11        outRect.top = firstAndlastRect.top;12        return;13    }1415    if (itemPosition == childCount - 1) {16        outRect.left = 0;17        outRect.right = firstAndlastRect.left;18        outRect.bottom = firstAndlastRect.bottom;19        outRect.top = firstAndlastRect.top;20        return;21    }2223    setOutRect(outRect, space);24}
1int j = DisplayUtils.dp2px(this, 15);2Rect firstAndLastRect = new Rect(j, i, i, 0);3HorizontalSpacesDecoration spacesDecoration = new HorizontalSpacesDecoration(rect, firstAndLastRect);4mRecyclerView.addItemDecoration(spacesDecoration);5List<Integer> integers = DataUtils.produceImageList(R.mipmap.ty1, 30);6ImageAdapter imageAdapter = new ImageAdapter(this, integers);7mRecyclerView.setAdapter(imageAdapter);

RecyclerViewSample:https://github.com/gdutxiaoxu/RecyclerViewSample

推荐阅读

装饰者模式及其应用

自定义 behavior - 完美仿 QQ 浏览器首页,美团商家详情页

技术人的未来在哪里

致刚入职场的你 - 程序员的成长笔记

Android 面试常见 - 二分查找算法题

Android 技术人

扫一扫,欢迎关注我的公众号。如果你有好的文章,也欢迎你的投稿。