通过RecyclerView提供的ItemDecoration 实现不同组条目分隔开间距,并且在间距处绘制吸顶条目分组
ItemDecoration类主要是三个方法:
public void onDraw()
在Item内容绘制之前绘制,可以理解成为Item绘制背景public void onDrawOver()
在Item内容绘制之后绘制,在Item之上绘制,覆盖在内容上public void getItemOffsets()
给Item设置类似Margin效果(在Margin填充的区域点击,ItemOnclickListener接受不到,因为设置的时候只是给Item ContentView设置点击事件)
吸顶Item具体实现
public class CeilingItemDecoration extends RecyclerView.ItemDecoration {
private final TextPaint textPaint; //绘制文字
private Paint mDividerPaint; //绘制组条目背景
private int sessionHeight=100;
private List<Integer> mList;
public void setList(List list) {
mList = list;
}
public CeilingItemDecoration() {
mDividerPaint = new Paint();
mDividerPaint.setColor(Color.GREEN);
textPaint = new TextPaint();
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setAntiAlias(true);
textPaint.setTextSize(80);
textPaint.setColor(Color.BLACK);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int position = parent.getChildAdapterPosition(view);
Integer i = mList.get(position);
if (i%10==0){
outRect.top=sessionHeight;
}else {
outRect.top=0;
}
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
int childCount = parent.getChildCount();
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int last=0;
for (int i = 0; i < childCount ; i++) {
View childAt = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(childAt); //获取实际逻辑的位置,而并非recyclerView 中显示的第几个条目
int num = mList.get(position);
num=num/10;
int max = Math.max(100, childAt.getBottom());
c.drawRect(left,childAt.getBottom()-max+last,right,childAt.getBottom()-max+100+last,mDividerPaint);
c.drawText(num+"",0,childAt.getBottom()-max+100+last,textPaint);
//判断是否是一个组的最后一个条目,如果是,则记录每个组最后一个条目的底部位置
if (i== childCount-1||mList.get(position)/10 ==mList.get(position+1)/10){
continue;
}
last = childAt.getBottom();
}
}
}