两种方案:
1.在子布局文件中在相应的位置添加一条分割线。
2.使用RecyclerView提供的addItemDecoration方法设置自己定义的分割线。
使用自己定义的分割线其实是android已经提供了ItemDecoration这个类,供我们去复写。
定义自己的分割线,有两步:1.绘制分割线 2.设置分割线
对应了ItemDecoration中的两个方法:onDraw(),getItemOffsets();
在onDraw()方法中我们绘制对应的分割线,主要根据布局方向来绘制
/**
* 绘制纵向的横线
*
*@paramcanvas
*@paramparent
*/
private voiddrawVertical(Canvas canvas, RecyclerView parent) {
final intleft = parent.getPaddingLeft();
final intright = parent.getMeasuredWidth() - parent.getPaddingRight();
final intchildSize = parent.getChildCount();
for(inti =0; i < childSize; i++) {
finalView child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final inttop = child.getBottom();
final intbottom = top +mItemSize;
canvas.drawRect(left, top, right, bottom,paint);
}
}
/**
* 绘制横向的分割线
*
*@paramcanvas
*@paramparent
*/
private voiddrawHorizatal(Canvas canvas, RecyclerView parent) {
final inttop = parent.getPaddingTop();
final intbottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
final intchildSize = parent.getChildCount();
for(inti =0; i < childSize; i++) {
finalView child = parent.getChildAt(i);
final intleft = child.getRight();
final intright = left +mItemSize;
canvas.drawRect(left, top, right, bottom,paint);
}
}
在getItemOffsets()方法中我们设置分割线的
if(mOrientation== LinearLayout.HORIZONTAL) {
outRect.set(0,0,0,mItemSize);
}else{
outRect.set(0,0,mItemSize,0);
}