Android 我眼中的自定义View(1)

做为一名Android开发者,自定义View应该是我们工作中绕不开的话题,毕竟系统提供的View有限,有时很难满足我们的需求,此时就需要结合具体的场景来编写自定义View,通过自定义View不仅可以实现特定的效果,还可以简化代码。自定义View的过程,也是我们自己造小轮子的过程,说不定在你的其它项目中就可以用到,对提高生产力还是大大有帮助的。

虽说自定义View是工作中绕不开的话题,但也是Android中最容易把开发者绕进去的知识点,经历过了从入门到放弃的再重新入门的辛酸过程,也该是用正确的姿势学习自定义View了。

View是什么呢?……就是Android中所有控件的基类,我们经常听到的ViewGroup也是View的一个子类。

直接上来就说如何自定义View未免有些空泛,所以我们从View底层的工作原理开始聊起,知其然也要知其所以然。App中我们所用到看到的一个个控件,都要经过measure(测量)、layout(布局)、draw(绘制)三大流程才会呈现在我们的眼前。其中measure用来测量View的大小,layout用来确定被测量后的View最终的位置,draw则是将View渲染绘制出来。其实View的工作流程在我们生活中也能找到类似的原型,比如,我们要画一个西瓜,首先要确定西瓜的大小,接下来要确定画在纸上的那个位置,最后才进行绘制。

在分析View的工作流程前,我们先要了解一个重要的知识点—MeasureSpec,MeasureSpec代表一个View的测量规格,它是一个32位的int值,高两位代表测量模式(SpecMode),低30位代表在对应测量模式下的大小(SpecSize)。通过MeasureSpec的getMode()、getSize()方法可以得到对应View宽\高的测量模式以及大小。
SpecMode,即测量模式有以下三种:

  • EXACTLY:父容器已经检测出View所需要的精确大小,此时View的大小就是SpecSize,对应于LayoutParams中的具体数值和match_parent两种类型。
  • AT_MOST:父容器指定了一个可用的大小即SpecSize,View的大小由其具体的实现决定,但不能大于SpecSize,对用于LayoutParams中的wrap_content。
  • UNSPECIFIED:父容器不对View大小做限制,View需要多大就给多大,这种测量模式一般用于系统内容,在我们自定义View中很少用到。

View的MeasureSpec是如何确定的呢?其实是由View自身的LayoutParams和父容器的MeasureSpec共同决定的。具体的细节我们来看源码,在ViewGroup中有一个measureChildWithMargins方法:

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

在measureChildWithMargins()方法中,通过getChildMeasureSpec()方法得到了View宽\高对应的测量模式childWidthMeasureSpec 、childHeightMeasureSpec,接下来重点看getChildMeasureSpec()的实现细节:

/**
  * @param spec 父View宽/高的测量规格
  * @param padding 父View在宽/高上已经占用的空间大小
  * @param childDimension 子View的宽/高
  */
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);//得到父View在宽/高上的测量模式
        int specSize = MeasureSpec.getSize(spec);//得到父View在对应测量模式下的宽/高

        int size = Math.max(0, specSize - padding);//计算子View在宽/高上可用的空间大小

        int resultSize = 0;
        int resultMode = 0;
        // 开始根据父View的测量规格以及子View的LayoutParams判断子View的测量规格
        switch (specMode) {
        // 当父View的测量模式为精确的大小时(包括具体的数值和match_parent两种)
        case MeasureSpec.EXACTLY:
            // 如果子View的LayoutParams的宽/高是固定的数值,那么它的测量模式为MeasureSpec.EXACTLY,
            // 大小为LayoutParams对应的宽/高数值,这样测量规格就确定了。
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } 
            // 如果子View的LayoutParams的宽/高为match_parent,那么子View的宽/高和父View尺寸相等,即为size,
            // 因为父View的尺寸已经确定,则子View的测量模式为MeasureSpec.EXACTLY。
            else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            }
            //  如果子View的LayoutParams的宽/高为wrap_content,就是说子View想根据实现方式来自己确定自己的大小,
            // 这个当然可以, 但是宽/高不能超过父View的尺寸,最大为size,则对应的测量模式为MeasureSpec.AT_MOST。
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // 当父View的测量模式为最大模式时,即父View目前也不知道自己的具体大小,但不能大于size
        case MeasureSpec.AT_MOST:
            // 既然子View的宽/高已经确定,虽然父View的尺寸尚未确定也要优先满足子View,
            // 则子View的宽/高为自身大小childDimension,对应的测量模式为MeasureSpec.EXACTLY。
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } 
            // 如果子View的LayoutParams的宽/高为match_parent,虽说父View的大小为size,但具体的数值并不能确定,
            // 所以子View宽/高不能超过父View的最大尺寸,即size,
            // 此时子View的宽高为最大为size,则对应的测量模式为MeasureSpec.AT_MOST
            else if (childDimension == LayoutParams.MATCH_PARENT) 
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } 
            // 如果子View的LayoutParams的宽/高为wrap_content,即子View想自己来决定自己的大小,这个当然可以
            // 同理,因为父View尺寸的不确定性,所以子View最终自我决定的尺寸不能大于size,
            // 对应的测量模式为MeasureSpec.AT_MOST。
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // 这种情况下,View的尺寸不受任何限制,主要用于系统内部,在我们日常开发中几乎用不到,就不分析了。
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //根据最终子View的测量大小和测量模式得到相应的测量规格。
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

所以View的测量规格是由自身的LayoutParams和父View的MeasureSpec共同决定的,它们之间具体的组合关系如下图:

《Android 我眼中的自定义View(1)》 此图来自互联网

既然搞清楚了MeasureSpec是怎么回事,接下来具体来看一下View的工作流程measure、layout、draw。

1、measure

首先测量过程要区分是View还是ViewGroup,如果只是单纯的View,则是需要测量自身就好了,如果是ViewGroup则需要先测量自身,再去递归测量所有的的子View。
1.1、当自定义View是单纯的View时
在View类中有如下方法:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
}

View通过该方法来进行大小测量,但是这是final方法,我们并不能重写,但是在它内部调用了View类的另外一个方法:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

好熟悉的感觉,这就是我们在自定义View的时候通常重写的onMeasure()方法。
其中setMeasuredDimension()方法,用来存储测量后的View的宽/高,存储之后,我们才可以调用View的getMeasuredWidth()、getMeasuredHeight()的到对应的测量宽/高。
重点看一下其中的getDefaultSize()方法:

/**
 * @param size View的默认尺寸
 * @param measureSpec View的测量规格
 */
public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

可以发现,当View的测量模式为MeasureSpec.AT_MOST、MeasureSpec.EXACTLY时,它最终的测量尺寸都为specSize ,竟然相等。再结合上边的MeasureSpec关系图对比下,可以看到当View最终的测量规格为MeasureSpec.AT_MOST时,其最终的尺寸为父View的尺寸。所以当自定义View在布局中的使用wrap_content和match_parent时的效果是一样的,View都将占满父View剩余的空间,但这并不是我们愿意看到的,所以我们需要在View的布局宽/高为wrap_content时,重新计算View的测量尺寸,其它情况下直接使用系统的测量值即可,重新测量的模板代码如下:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);

        //View的布局参数为wrap_content时,需要重新计算的View的测量宽/高
        int measureWidth = 0;
        int measureHeight = 0;

        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            //确定measureWidth、measureHeight
            setMeasuredDimension(measureWidth, measureHeight);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            //确定measureWidth
            setMeasuredDimension(measureWidth, heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            //确定measureHeight
            setMeasuredDimension(widthSpecSize, measureHeight);
        }
    }

至于如何确定measureWidth、measureHeight的值,就需要结合具体的业务需求了。
1.2、当自定义View是一个ViewGroup时
ViewGroup是一个抽象类,继承与View类,但它没有重写onMeasure()方法,所以需要ViewGroup的子类去实现onMeasure()方法以进行具体测量。既然View类对onMeasure()方法方法做了统一的实现,为什么ViewGroup类没有呢?因为View类不牵扯子View的布局,而ViewGroup中的子View可能有不同的布局情况,实现细节也有差别,所以无法做统一的处理,只能交给子类根据业务需求来重写。
在ViewGroup类里有一个measureChildren()方法:

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

该方法通过遍历子View,进而调用measureChild()方法得到子View的测量规格:

protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

可以看到该方法和我们上边分析的measureChildWithMargins()方法类似,都是通过getChildMeasureSpec()完成对子View规格的测量。所以一般情况下,我们自定义View如果继承ViewGroup,则需要在重写onMeasure()方法时首先进行measureChildren()操作来确定子View的测量规格。

1.1中我们提到,如果View在布局中宽/高为wrap_content时,需要重写onMeasure(),来重新计算View的测量宽/高,同样的道理,当我们自定义的View是一个ViewGroup的话也需要重新计算ViewGroup的测量宽/高,当然这里的计算一般要考虑子View的数量以及测量规格等情况。

2、layout

layout的作用是来确定View本身的位置,在View类中源码如下:

public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }

其中有这么一段:

boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

用来设置View四个边的位置,即mLeft、mTop、mBottom、mRight的值,这样也就确定了View本身的位置。
接下来通过onLayout(changed, l, t, r, b);来确定子View在父View中的位置:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

是个空方法哦,所以当我们自定义ViewGroup时需要重写onLayout()方法,来确定子View的位置。View类中的layout方法有这么一段注释:

Derived classes should not override this method.
Derived classes with children should override onLayout.
In that method, they should call layout on each of their children.

大概的意思是这样的,View的派生类一般不需要重写layout方法,应该在其派生类中重写onLayout()方法,并在onLayout()方法中调用layout()方法来确定子View的位置。

其实,这也符合我们平时自定义View时如果继承ViewGroup时的情况,我们一般都会重写onLayout()方法,然后通过layout()方法确定子View的具体位置。
当我们自定义的View如果继承View类的话,一般就不需要重写onLayout()方法了哦,毕竟没有子View么。

执行完layout方法后,我们的View具体位置也就确定了,此时可以通过getWidth()、getHeight()方法得到View的最终宽/高:

public final int getWidth() {
        return mRight - mLeft;
    }

public final int getHeight() {
        return mBottom - mTop;
    }

还记得我们在分析measure过程时提到,通过getMeasuredWidth()、getMeasuredHeight()可以得到View的测量宽/高,这两组方法有什么区别呢?其实一般情况下View的测量宽/高和最终的宽/高相等,只是赋值的时间点不同,但在某些特殊的情况下就有差别了。拿getWidth()方法来说,它的返回值是mRight – mLeft,即View右边位置和左边位置的差值,我们假设一个自定义ViewGroup中某个子View的四边的位置分别为:l、t、r、b,一般情况下我们会这样确定子View的位置:

childView.layout(l, t, r, b);

这种情况View的测量宽度和最终宽度是相等的,但如果按照如下的写法:

childView.layout(l, t, r + 100, b);

此时View的最终宽度会比测量宽度大100px的。在measure过程中有一点需要注意,如果View的结构比较复杂,则可能需要多次的进行测量才能得到最终的测量结果,这也会导致我们得到的测量尺寸不准确。所以,所以要得到View最终的正确尺寸,应该通过getWidth()或者getHeight()方法。

3、draw

经历了measure、layout的过程,View的尺寸和位置已经确定,接下来就差最后一步了,那就是draw,具体的绘制流程是什么样的呢?查看一下View类中draw方法的源码:

public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * 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
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // we're done...
            return;
        }
        //此处省略N行代码......
}

绘制的流程很清晰,基本按照如下几个步骤:

  • 1、Draw the background 绘制View的背景 drawBackground(canvas)
  • 2、If necessary, save the canvas’ layers to prepare for fading 保存画布层,准备渐变
  • 3、Draw view’s content 绘制内容,也就是View自身 onDraw(canvas)
  • 4、Draw children 绘制子View dispatchDraw(canvas)
  • 5、If necessary, draw the fading edges and restore layers 绘制渐变,保存图层
  • 6、Draw decorations (scrollbars for instance) 绘制装饰物 onDrawForeground(canvas)
    我们关心的是步骤3、4的onDraw()和dispatchDraw()方法。
    先看onDraw()方法:
protected void onDraw(Canvas canvas) {
    }

是一个空方法,这也可以理解,毕竟不同的View呈现的效果不同,所以需要子类重写来实现具体的细节。当我们自定义View继承View类时,通常会重写onDraw()方法,来绘制线条或各种形状、图案等。

再看一下View类的dispatchDraw()方法:

protected void dispatchDraw(Canvas canvas) {
    }

依然是空方法,需要子类去重写,所以ViewGroup类中重写了dispatchDraw()方法,遍历所有的子View,其中有一行代码是drawChild(canvas, transientChild, drawingTime);正是用来绘制子View的,再看下细节:

protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

其中child.draw(canvas, this, drawingTime);是子View调用了View类的draw()方法,则子View得到了最终的绘制。同样的道理ViewGroup中的所有子View得到绘制。所以当我们自定义的View是ViewGroup的子类时,必要时可以考虑重写dispatchDraw()方法来绘制相应的内容。

到这里我们View的工作流程就分析完毕了,掌握这些基本的原理只是第一步,但也是必须的,继续加油吧。

    原文作者:SheHuan
    原文地址: https://www.jianshu.com/p/0c1e5e2ee14a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞