1.背景
RecyclerView 是谷歌 V7 包下新增的控件,用来替代 ListView 和 GridView 使用的一个控件。在使用的过程中,往往需要使用到 divider 的效果 ( item 之间的分割线 )。而 RecyclerView 并不像 ListView 一样自带有 divider 的属性。而是需要用到 RecyclerView.ItemDecoration 这样一个类,但是 ItemDecoration 是一个抽象类,而且 android 内部并没有给它做一些效果的实现。那么就需要我们自己去继承并实现其中的方法,本文讲述的就是在 GridLayoutManager 和 LinearLayoutManager 下如何去实现 ItemDecoration。至于 RecyclerView.ItemDecoration 的具体分析,大家可以去看看这篇文章 深入理解 RecyclerView 系列之一:ItemDecoration 这里不作过多的阐述。
2.实现基本的 Item 的 divider
2.1 创建 SpacesItemDecoration
创建一个类 SpacesItemDecoration 继承于 RecyclerView.ItemDecoration ,实现其中的 onDraw 和 getItemOffsets 方法,在这里我们的设计是左右距离相等,上下距离相等。
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int leftRight;
private int topBottom;
public SpacesItemDecoration(int leftRight, int topBottom) {
this.leftRight = leftRight;
this.topBottom = topBottom;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
}
}
在这里我们主要实现的方法是 onDraw 和 getItemOffsets, getItemOffsets 主要是确定 divider 的范围,而 onDraw 是对 divider 的具体实现。
2.2 LinearLayoutManager 下 divider 的实现
首先在 getItemOffsets 方法中需要判断当前的 RecyclerView 所采用的哪种 LayoutManager。这里要注意的是 GridLayoutManager 是继承 LinearLayoutManager 的,所以需要先判断是否为 GridLayoutManager。
private SpacesItemDecorationEntrust getEntrust(RecyclerView.LayoutManager manager) {
SpacesItemDecorationEntrust entrust = null;
//要注意这边的GridLayoutManager是继承LinearLayoutManager,所以要先判断GridLayoutManager
if (manager instanceof GridLayoutManager) {
entrust = new GridEntrust(leftRight, topBottom, mColor);
} else {//其他的都当做Linear来进行计算
entrust = new LinearEntrust(leftRight, topBottom, mColor);
}
return entrust;
}
然后我们来看具体的实现,首先判断是 VERTICAL 还是 HORIZONTAL 。对于 VERTICAL,每一个 item 必需的是 top,left 和 right,但是最后一个 item 还需要 bottom。而对于 HORIZONTAL ,每一个 item 必需的是 top,left 和 bottom,但是最后一个 item 还需要 right。
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
//竖直方向的
if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
//最后一项需要 bottom
if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
outRect.bottom = topBottom;
}
outRect.top = topBottom;
outRect.left = leftRight;
outRect.right = leftRight;
} else {
//最后一项需要right
if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
outRect.right = leftRight;
}
outRect.top = topBottom;
outRect.left = leftRight;
outRect.bottom = topBottom;
}
}
就这样,divider 效果就实现了(当然是没有任何的颜色的)。调用方式只需要。
int leftRight = dip2px(7);
int topBottom = dip2px(7);
rv_content.addItemDecoration(n