ItemDecoration深刻解析与实战(一)——源码分析

一 概述

ItemDecorationRecyclerView 中的一个抽象静态内部类。java

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.canvas

这是官网对 ItemDecoration 的描述,简单来讲就是能够为 RecyclerView的每个 ItemView 进行一些特殊的绘制或者特殊的布局。从而咱们能够为 RecyclerView 添加一些实用好玩的效果,好比分割线,边框,饰品,粘性头部等。bash

此文会分析ItemDecoration 的使用及原理,而后进行一些Demo的实现,包括分割线,网格布局的边框,以及粘性头部。app

二 方法

1. 方法概述

ItemDecoration中的实际方法只有6个,其中有3个是重载方法,都被标注为 @deprecated,即弃用了,这些方法以下ide

修饰符 返回值类型 方法名 标注
void public onDraw(Canvas c, RecyclerView parent, State state)
void public onDraw(Canvas c, RecyclerView parent) @deprecated
void pulbic onDrawOver(Canvas c, RecyclerView parent, State state)
void public onDrawOver(Canvas c, RecyclerView parent) @deprecated
void public getItemOffsets(Rect outRect, View view, RecyclerView parent, State state)
void public getItemOffsets(Rect outRect, View view, RecyclerView parent) @deprecated

2. getItemOffsets

除了 getItemOffsets 方法,其余方法的默认实现都为空,而 getItemOffsets 的默认实现方法也很简单:布局

@Deprecated
        public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            outRect.set(0, 0, 0, 0);
        }
复制代码

两个getItemOffsets方法最终都是调用了上面实现,就一行代码,若是咱们自定义过 ItemDecoration 的话,就会知道,咱们能够为 outRect 设置四边的大小来为 itemView 设置一个偏移量. 这个偏移量有点相似于 View 的margin,看下面的图1:ui

RecyclerView&Child.png

图片很清晰的表示了 ItemView 的结构(该图不是特别精确,后面会说到),这是只有一个 Child 的状况,咱们从外往里看:this

  1. 最外的边界即 RecyclerView 的边界
  2. 红色部分是 RecyclerView 的 Padding,这个咱们应该能理解
  3. 橙色部分是咱们为 ItemView 设置的 Margin,这个相信写过布局都能理解
  4. 蓝色部分就是咱们在 getItemOffsets方法中给 outRect对象设置的值
  5. 最后的的黄色部分就是咱们的 ItemView 了

整体就是说,getItemOffsets中设置的值就至关于 margin 的一个存在。"图说无凭",接下来就结合源码讲解一下这个图的"依据"。首先看一下 getItemOffsets在哪里被调用了:spa

Rect getItemDecorInsetsForChild(View child) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        ...
        final Rect insets = lp.mDecorInsets;
        insets.set(0, 0, 0, 0);
        final int decorCount = mItemDecorations.size();
        for (int i = 0; i < decorCount; i++) {
            mTempRect.set(0, 0, 0, 0);
            mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);  //被调用
            insets.left += mTempRect.left;
            insets.top += mTempRect.top;
            insets.right += mTempRect.right;
            insets.bottom += mTempRect.bottom;
        }
        lp.mInsetsDirty = false;
        return insets;
 }
复制代码

RecyclerView源码中,这是 getItemOffsets惟一被调用的地方,代码也很简单,就是将 RecyclerView中全部的(即经过addDecoration()方法添加的) ItemDecoration 遍历一遍,而后将咱们设在 getItemOffsets 中设置的四个方向的值分别累加并存储在insets这个Rect当中。那么这个 insets又在哪里被调用了呢,顺着方法继续跟踪下去:rest

public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();

    final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
    widthUsed += insets.left + insets.right;
    heightUsed += insets.top + insets.bottom;

    final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
            getPaddingLeft() + getPaddingRight()
                    + lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
            canScrollHorizontally());
    final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
           getPaddingTop() + getPaddingBottom()
                    + lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
            canScrollVertically());
    if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
        child.measure(widthSpec, heightSpec);
    }
}
复制代码

咱们看到,在 measureChildWithMargins方法中,将刚刚获得的 insets 的值与 Recyclerview 的 Padding 以及当前 ItemView 的 Margin 相加,而后做为 getChildMeasureSpec的第三个参数传进去:

public static int getChildMeasureSpec(int parentSize, int parentMode, int padding,
    int childDimension, boolean canScroll) {
    int size = Math.max(0, parentSize - padding);
    int resultSize = 0;
    int resultMode = 0;
    //...省略部分代码
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
复制代码

getChildMeasureSpec方法的第三个参数标注为 padding ,在方法体这个 padding 的做用就是计算出 size 这个值,这个 size是就是后面测量中 Child(ItemView) 能达到的最大值。

也就是说咱们设置的 ItemView 的 Margin 以及ItemDecoration.getItemOffsets中设置的值到头来也是跟 Parent 的 Padding 一块儿来计算 ItemView 的可用空间,也就印证了上面的图片,在上面说了该图不精确就是由于

  • parent-padding
  • layout_margin
  • insets(all outRect)

他们是一体的,并无划分红一段一段这样,图中的outRect也应该改成insets,可是图中的形式能够更方便咱们理解。

3. onDraw

public void onDraw(Canvas c, RecyclerView parent, State state) {
        onDraw(c, parent);
    }

    /**
     * @deprecated Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
     */
    @Deprecated
    public void onDraw(Canvas c, RecyclerView parent) {
    }
复制代码

onDraw方法有两个重载,一个被标注为 @deprecated,即弃用了,咱们知道,若是重写了 onDraw,就能够在咱们上面的 getItemOffsets中设置的范围内绘制,知其然还要知其因此然,咱们看下源码里面是怎样实现的 #RecyclerView.java

@Override
    public void onDraw(Canvas c) {
        super.onDraw(c);

        final int count = mItemDecorations.size();
        for (int i = 0; i < count; i++) {
            mItemDecorations.get(i).onDraw(c, this, mState);
        }
    }

复制代码

ReyclerViewonDraw方法中,将会把全部 DecorationonDraw方法调用一遍,并且会把Recyclerview#onDraw(Canvas)方法中的Canvas传递给Decoration#onDraw,也就是说咱们在Decoration中拿到了整个 RecyclerView 的 Canvas,那么咱们基本就能够随意绘制了,可是咱们使用中会发现,咱们绘制的区域若是在 ItemView 的范围内就会被盖住,这是为何呢?

因为View的绘制是先执行 draw(Canvas)再到onDraw(Canvas)的,咱们复习一波自定义View的知识,看下View的绘制流程: #View.java

public void draw(Canvas canvas) {
      
        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)

        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);   //注释1

            // Step 4, draw the children
            dispatchDraw(canvas);        //注释2
            ...
            // we're done... return; } } 复制代码

咱们直接看注释1与注释2那段,能够看到,View的绘制是先绘制自身(onDraw调用),而后再绘制child,因此咱们在 Decoration#onDraw中绘制的界面会被 ItemView 遮挡也是理所固然了。

因此咱们在绘制中就要计算好绘制的范围,使绘制范围在上面彩图中蓝色区域内,即getItemOffsets设置的范围内,避免没有显示或者过度绘制的状况。

4.onDrawOver

public void onDrawOver(Canvas c, RecyclerView parent, State state) {
        onDrawOver(c, parent);
    }

    /**
     * @deprecated
     * Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)}
     */
    @Deprecated
    public void onDrawOver(Canvas c, RecyclerView parent) {
    }
复制代码

onDrawOveronDraw很是相似,也是两个重载,一个被弃用了,看名称咱们就基本能知道这个方法的用途,它是用于补充 onDraw 的一个方法,因为onDraw会被 ItemView 覆盖,因此咱们想要绘制一些漂浮在RecyclerView顶层的装饰就没法实现,因此就有了这个方法,他是在 ItemView 绘制完毕后才会被调用的,看下源码的实现: #RecyclerView.java

@Override
    public void draw(Canvas c) {
        super.draw(c);

        final int count = mItemDecorations.size();
        for (int i = 0; i < count; i++) {
            mItemDecorations.get(i).onDrawOver(c, this, mState);
        }
        ...
    }
复制代码

super.draw(c) 就是咱们在上面分析的View#draw(Canvas)方法,会调用一系列的绘制流程,包括onDraw(ItemDecoration的onDraw)以及dispatchDraw(ItemView的绘制),走完这些流程后才会调用Decoration#onDrawOver方法.

到此,咱们就能够得出 onDraw>dispatchDraw(ItemView的绘制)>onDrawOver的执行流程。

5. 总结

  1. getItemOffsets用于提供一些空间(相似Margin)给 onDraw绘制
  2. onDraw方法绘制的内容若是在 ItemView 的区域则可能被覆盖(没效果)
  3. onDraw>dispatchDraw(ItemView的绘制)>onDrawOver从左到右执行

三 实战

实战将会从易到难进行几个小的Demo练习。 因为这篇文章内容已经比较充实了,就把实战部分放到下篇讲解。

感谢你的阅读,因为水平有限,若有错误恳请提醒。

相关文章
相关标签/搜索