2、ItemTouchHelper.setupCallbacks 方法分析
在 ItemTouchHelper.setupCallbacks 方法中 , 调用了
mRecyclerView.addItemDecoration(this);
方法 , 为当前的 RecyclerView 设置条目装饰 , 该装饰可以在条目组件 底部 上层 绘制 Canvas 图形 , 具体的方法如下 :
public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild2, NestedScrollingChild3 { /** * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can * affect both measurement and drawing of individual item views. * * <p>Item decorations are ordered. Decorations placed earlier in the list will * be run/queried/drawn first for their effects on item views. Padding added to views * will be nested; a padding added by an earlier decoration will mean further * item decorations in the list will be asked to draw/pad within the previous decoration's * given area.</p> * * @param decor Decoration to add * @param index Position in the decoration chain to insert this decoration at. If this value * is negative the decoration will be added at the end. */ public void addItemDecoration(@NonNull ItemDecoration decor, int index) { if (mLayout != null) { mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or" + " layout"); } if (mItemDecorations.isEmpty()) { setWillNotDraw(false); } // 将多个 ItemDecoration 添加到 mItemDecorations 集合中 if (index < 0) { mItemDecorations.add(decor); } else { mItemDecorations.add(index, decor); } markItemDecorInsetsDirty(); // 开始进行绘制 requestLayout(); } }
3、RecyclerView.ItemDecoration 源码分析
ItemDecoration 是抽象类 , 核心逻辑必须由子类实现后才可以使用 ;
void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull State state) 方法是绘制方法 , 在该方法中调用了 void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent) 方法 , public abstract static class ItemDecoration { public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull State state) { onDraw(c, parent); } @Deprecated public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent) { } }
参考 Android 官方提供的 RecyclerView.ItemDecoration 的实现类 DividerItemDecoration , 该类中重写了 onDraw 方法 , 其中调用了 drawVertical 绘制垂直分割线 , 调用了 drawHorizontal 方法绘制水平分割线 ;
public class DividerItemDecoration extends RecyclerView.ItemDecoration { @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if (parent.getLayoutManager() == null || mDivider == null) { return; } if (mOrientation == VERTICAL) { // 绘制垂直分割线 drawVertical(c, parent); } else { // 绘制水平分割线 drawHorizontal(c, parent); } } }
在上述 drawVertical 和 drawHorizontal 方法中 , 利用 Canvas 进行绘图 ;
在 RecyclerView.ItemDecoration 中 , 不仅仅只能绘制分割线 , 可以绘制任何图形 , 图片 , 颜色 , 与自定义组件绘制功能一样强大 ;