最近项目中有一个GridView棋盘格式的布局需求。刚好考虑到性能优化的问题,打算这次使用RecyclerView去代替GridView。关于RecyclerView中的例子网上有些很多。无非是设置一下Adapter,通过layoutManager规范一下View的显示方式:线性,网格,瀑布流等。但是设置Item分割线的时候网上提供的资料大多是调用系统Attr中的listDivider 再通过自定义Drawble构造样式。但是这样处理完之后发现自己之前listview的Divider样式也被改了。于是打算换种方式进行替换。自己去实现抽象类ItemDecoration中的几个方法来画出View中的分隔线
```
public classDividerLineextendsRecyclerView.ItemDecoration {
//画笔
privatePaintpaint;
//分割线颜色
private intcolor;
//分割线尺寸
private intsize;
publicDividerLine() {
paint=newPaint();
}
@Override
public voidonDrawOver(Canvas c,RecyclerView parent,RecyclerView.State state) {
super.onDrawOver(c,parent,state);
drawHorizontal(c,parent);
drawVertical(c,parent);
}
/**
*设置分割线颜色
*
*@paramcolor颜色
*/
public voidsetColor(intcolor) {
this.color= color;
paint.setColor(color);
}
/**
*设置分割线尺寸
*
*@paramsize尺寸
*/
public voidsetSize(intsize) {
this.size= size;
}
//绘制垂直分割线
protected voiddrawVertical(Canvas c,RecyclerView parent) {
final inttop = parent.getPaddingTop();
final intbottom = parent.getHeight() - parent.getPaddingBottom();
final intchildCount = parent.getChildCount();
for(inti =0;i < childCount;i++) {
finalView child = parent.getChildAt(i);
finalRecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final intleft = child.getRight() + params.rightMargin;
final intright = left +size;
c.drawRect(left,top,right,bottom,paint);
}
}
//绘制水平分割线
protected voiddrawHorizontal(Canvas c,RecyclerView parent) {
final intleft = parent.getPaddingLeft();
final intright = parent.getWidth() - parent.getPaddingRight();
final intchildCount = parent.getChildCount();
for(inti =0;i < childCount;i++) {
finalView child = parent.getChildAt(i);
finalRecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final inttop = child.getBottom() + params.bottomMargin;
final intbottom = top +size;
c.drawRect(left,top,right,bottom,paint);
}
}
}
```