个人总结,做个记录。
如图,一般来说,item之间都应该有分界线。但是RecyclerView并没有提供divider这样的属性。在API中,提供了RecyclerView.ItemDecoration这样一个内部类。API文档是这样描述的:
An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter’s data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.
All ItemDecorations are drawn in the order they were added, before the item views (in onDraw() and after the items (in onDrawOver(Canvas, RecyclerView, RecyclerView.State).
也就是说这个绘制是按照他们的添加顺序进行的,并且是发生在item view的绘制之前。
这是一个抽象类,是需要我们自己去具体实现的。
1. 从DividerItemDecoration开始
从API 25开始,新增了一个具体的实现类DividerItemDecoration
。
DividerItemDecoration is a RecyclerView.ItemDecoration that can be used as a divider between items of a LinearLayoutManager. It supports both HORIZONTAL and VERTICAL orientations.
从介绍来看,这是一个用于LinearLayout的分割线
mDividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
mLayoutManager.getOrientation());
recyclerView.addItemDecoration(mDividerItemDecoration);
其实ItemDecoration
还提供了另外一个子类ItemTouchHelper
,这是在API 22.2.0中增加的。这个类主要是用来处理RecyclerView的滑动拖拉事件的,暂且不论。
先来看看ItemDecoration这个抽象类:
public static abstract class ItemDecoration {
public void onDraw(Canvas c, RecyclerView parent, State state) {
onDraw(c, parent);
}
public void onDrawOver(Canvas c, RecyclerView parent, State state) {
onDrawOver(c, parent);
}
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
getI