Android:View体系之UI 的绘制流程及原理 (源码分析+掌握,看这一篇就足够!)

转载请标明出处!

目录

一 概述

1.1 Android的View继承关系图

1.2 Android的视图坐标

1.2.1 安卓坐标系

1.2.2 视图坐标系

1.2.3 常用方法

二 View的事件分发

三 View的工作流程

3.1 概述

3.2 测量

3.2.1 预备知识MeasureSpec(重要)

3.2.2 MeasureSpec的SpecMode分类(模式)

3.2.3 测绘过程

3.2.4 测绘源码分析,以DecorView为例

3.3 布局

3.3.1 布局源码分析,以FrameLayout为例

3.4 绘制

3.4.1 绘制 源码分析,以FrameLayout为例


一 概述

1.1 Android的View继承关系图

View是安卓所有控件的父基类。

 

1.2 Android的视图坐标

1.2.1 安卓坐标系

获取办法:MotionEvent提供的getRawX()和getRawY();

1.2.2 视图坐标系

1.2.3 常用方法

View获取自身宽高

getHeight()获取View自身高度
getWidth()获取View自身宽度

View到其父控件(ViewGroup)的距离:

getTop()获取View自身顶边到其父布局顶边的距离
getLeft()获取View自身左边到其父布局左边的距离
getRight()获取View自身右边到其父布局左边的距离
getBottom()获取View自身底边到其父布局顶边的距离

 

MotionEvent提供的方法

我们看上图那个深蓝色的点,假设就是我们触摸的点,我们知道无论是View还是ViewGroup,最终的点击事件都会由onTouchEvent(MotionEvent event)方法来处理,MotionEvent也提供了各种获取焦点坐标的方法:

getX()获取点击事件距离控件左边的距离,即视图坐标
getY()获取点击事件距离控件顶边的距离,即视图坐标
getRawX()获取点击事件距离整个屏幕左边距离,即绝对坐标
getRawY()取点击事件距离整个屏幕顶边的的距离,即绝对坐标

二 View的事件分发

点击事件分发:点击屏幕就会产生触摸事件,这个事件被封装成了一个类:MotionEvent。当这个MotionEvent产生后,系统就会将这个MotionEvent传递给View的各个层级,MotionEvent在View层级传递的过程,就是点击事件分发。

点击事件有三个重要的方法:

dispatchTouchEvent(MotionEvent ev)用来进行事件的分发
onInterceptTouchEvent(MotionEvent ev)用来进行事件的拦截,在dispatchTouchEvent()中调用,需要注意的是View没有提供该方法
onTouchEvent(MotionEvent ev)用来处理点击事件,在dispatchTouchEvent()方法中进行调用

点击事件分发的这三个重要方法的关系,用伪代码来简单表示就是:

 public boolean dispatchTouchEvent(MotionEvent ev) {
 boolean result=false;
 if(onInterceptTouchEvent(ev)){
       result=super.onTouchEvent(ev);
  }else{
       result=child.dispatchTouchEvent(ev);
 }
 return result;

 这个U型图就很好的解释了事件分发:


 

总结:dispatchTouchEvent代表分发事件,onInterceptTouchEvent()代表拦截事件,onTouchEvent()代表消耗事件,由自己处理。


三 View的工作流程

3.1 概述

measure:测量View的宽高;测量;

layout:用来确定View的位置;布局;

draw:则用来绘制View;绘制;

3.2 测量

3.2.1 预备知识MeasureSpec(重要)

       MeasureSpec是View的静态内部类;View的测量就是测量View的宽高,而View的宽高被封装到了MeasureSpec里面。

       测量的过程实际上就是如何确定View的MeasureSpec的过程,而MeasureSpec主要包含两个参数:模式+尺寸。

       MeasureSpec是一个32位int值,前2位表示SpecMode即模式  ,后30位表示SpecSize即尺寸。

 

3.2.2 MeasureSpec的SpecMode分类(模式)

UNSPECIFIED

public static final int UNSPECIFIED = 0 << MODE_SHIFT; 00000000000000000000000000000000

父容器不对View做任何限制,系统内部使用

EXACTLY  
public static final int EXACTLY     = 1 << MODE_SHIFT; 01000000000000000000000000000000
父容器检测出View的大小,Vew的大小就是SpecSize LayoutPamras match_parent 固定大小

AT_MOST
public static final int AT_MOST     = 2 << MODE_SHIFT; 10000000000000000000000000000000
父容器指定一个可用大小,View的大小不能超过这个值,LayoutPamras wrap_content

 

3.2.3 测绘过程

ViewGroup的测绘过程 :

measure --> onMeasure(测量子控件的宽高)--> setMeasuredDimension -->setMeasuredDimensionRaw(保存自己的宽高)


View的测绘过程:

measure --> onMeasure --> setMeasuredDimension -->setMeasuredDimensionRaw(保存自己的宽高)

 

3.2.4 测绘源码分析,以DecorView为例

首先在ViewRootImpl中,执行performMeasure方法:

   private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

点击mView.measure方法,会进入View的measure方法(标注1)(view的该方法为final,不能被重写),如下:


    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int oWidth  = insets.left + insets.right;
            int oHeight = insets.top  + insets.bottom;
            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
        }

        // Suppress sign extension for the low bytes
        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;

        // Optimize layout by avoiding an extra EXACTLY pass when the view is
        // already measured as the correct size. In API 23 and below, this
        // extra pass is required to make LinearLayout re-distribute weight.
        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
                || heightMeasureSpec != mOldHeightMeasureSpec;
        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
        final boolean needsLayout = specChanged
                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);

        if (forceLayout || needsLayout) {
            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back


                //这里!重要的onMeasure方法,终于找到你!
                //这里!重要的onMeasure方法,终于找到你!
                //这里!重要的onMeasure方法,终于找到你!

                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            // flag not set, setMeasuredDimension() was not invoked, we raise
            // an exception to warn the developer
            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
                throw new IllegalStateException("View with id " + getId() + ": "
                        + getClass().getName() + "#onMeasure() did not set the"
                        + " measured dimension by calling"
                        + " setMeasuredDimension()");
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
    }

代码有点多,不用全看。前半部分主要是取了缓存,然后执行了 onMeasure(widthMeasureSpec, heightMeasureSpec)方法。如果缓存没读到会进行缓存的一个设置。(关于缓存可以先忽略不用管,主要是对测量做一些优化)

紧接着上面的代码段中,点击主要的onMeasure方法一探究竟:

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

会发现,onMeasure方法里最主要调用了两个方法:setMeasuredDimension方法和getDefaultSize方法。先看下getDefaultSize方法:

 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;
    }

注意,可以看到,这里无论是AT_MOST模式还是EXACTLY模式,都是默认的specSize,所以我们在自定义View的时候,一定要重写onMeasure方法,否则match_parent和wrap_content属性时,将不起作用。

我们再来看看setMeasuredDimension方法里是什么:

    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int opticalWidth  = insets.left + insets.right;
            int opticalHeight = insets.top  + insets.bottom;

            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
            measuredHeight += optical ? opticalHeight : -opticalHeight;
        }
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
    }

可以看到,setMeasuredDimension方法里继续调用了setMeasuredDimensionRaw(measuredWidth, measuredHeight)方法,继续查看这个方法的详细:

    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
    }

谢天谢地,终于到头了!可以看到,该方法对宽高成员变量赋值以及设置了一个标记位。

不要因为走得太远而忘记了为何出发,我们是在ViewRootImpl中执行performMeasure方法中的mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)不断追溯来到这边的,所以measure(测量)实质上就是确定控件的宽和高。那么控件的宽和高,他们的值又是如何确定的呢?现在我们就需要查看mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)中的childWidthMeasureSpec, childHeightMeasureSpec这两个参数!

这边打个分割线便于大家理解,上方是mView.measure方法测量的源码过程解析,


接下来我们需要知道mView.measure方法的两个参数如何获取。

在ViewRootlmpl中,继续解读源码:

                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

                    if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
                            + " mHeight=" + mHeight
                            + " measuredHeight=" + host.getMeasuredHeight()
                            + " coveredInsetsChanged=" + contentInsetsChanged);

                     // Ask host how big it wants to be
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

可以看到,childWidthMeasureSpec,和childHeightMeasureSpec这两个参数由getRootMeasureSpec(mWidth, lp.width)方法和getRootMeasureSpec(mHeight, lp.height)得出。以第一个为例,mWidth表示的是窗口(PhoneWindow)的宽,第二个参数表示的是顶层View的本身的宽。参数有了,我们接下来再详细进入getRootMeasureSpec这个方法里一探究竟:

    /**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     *
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

注释写的很详细了,可以看到,该方法里对测量的view就行了switch判断,根据view的match_parent属性/wrap_content属性设置了measureSpec的不同模式(EXACTLY/AT_MOST)。

又这个方法我们可以得出结论:DecorView的MeasureSpec方法由窗口大小和自己的LayoutParams决定。具体的决定规则逻辑在如上代码中,具象下来可以总结如下:

继续分析。刚刚我们已经确定了这两个参数的由来。实际上这两个参数确定了DccorView的模式和尺寸(注意子view的测量还没有,过程才刚开始)。

继续分割一下避免混乱,上面是mView.measure方法的两个参数由来,


接下来我们继续分析mView.measure方法。

mView.measure(也就是View的measure方法,这里的mView就是DecorView)中调用onMeasure方法。我们知道DecorView实际上是集成FrameLayout的,所以我们直接去FrameLayout中看看这个onMeasure方法的具体实现:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));

        count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }

很符合我们心理预期,FrameLayout作为容器,肯定会包含很多的子View,可以看到上面的源码方法里,也对其所有的子View进行了遍历,不难想象,它将对它的所有子View进行测量。为了验证猜想,继续点击该方法中的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);
    }

该方法中增加了对padding的处理,很容易理解不赘述。

看child.measure(childWidthMeasureSpec, childHeightMeasureSpec)方法。验证了我们的猜想,从名字就可以看出,开始对FrameLayout中的子View进行宽高 测量了。

这里有个非常重要的点:getChildMeasureSpec方法,即对子View的MeasureSpec的获取,点击看详细的getChildMeasureSpec方法实现:

    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

这个方法有点长,不要怕。可以看到该方法的第一个参数表示父容器的MeasureSpec的值(父容器的模式和尺寸),第二个参数padding就不说了,第三个参数表示该view本身的尺寸。该方法就通过对父容器的模式的判断,确定该子View的模式和尺寸。具体的判断逻辑可看如上代码,不详细赘述了,总结如下:

在对所有的子控件测量完成后,FrameLayout开始需要最终确定自己的宽高。继续看FrameLayout中的onMeasure方法,看它的后半段,我再粘贴下关键代码:

      // Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));


count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }

可以看到,FrameLayout找到所有子控件中,最底部子控件的高,和最右边子控件的高。由此我们最终确定了Framelayout的宽高!


3.3 布局

源码看起来总是费力些,先总结如下:

View :

调用View.layout来确定自己的位置,即确定mLeft,mTop,mRight,mBottom的值,获得4个点的位置。

ViewGroup:

调用View.layout来确定自己的位置,再调用onLayout确定子View的位置。

 

3.3.1 布局源码分析,以FrameLayout为例

查看FrameLayout的onLayout方法如下:

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

点击查看 layoutChildren方法:

    void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
        final int count = getChildCount();

        final int parentLeft = getPaddingLeftWithForeground();
        final int parentRight = right - left - getPaddingRightWithForeground();

        final int parentTop = getPaddingTopWithForeground();
        final int parentBottom = bottom - top - getPaddingBottomWithForeground();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = DEFAULT_CHILD_GRAVITY;
                }

                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                        lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        if (!forceLeftGravity) {
                            childLeft = parentRight - width - lp.rightMargin;
                            break;
                        }
                    case Gravity.LEFT:
                    default:
                        childLeft = parentLeft + lp.leftMargin;
                }

                switch (verticalGravity) {
                    case Gravity.TOP:
                        childTop = parentTop + lp.topMargin;
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                        lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = parentBottom - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = parentTop + lp.topMargin;
                }

                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

 可以看到, layoutChildren方法中对子View进行了遍历,对子控件进行位置的摆放。而对子控件的摆放,调用的是子控件的layout方法,也就是上面代码的最后一行。布局就是这么简单。


3.4 绘制


ViewGroup 绘制步骤:

绘制背景 drawBackground(canvas)

绘制自己onDraw(canvas)

绘制子View dispatchDraw(canvas)

绘制前景,滚动条等装饰onDrawForeground(canvas)

 

View绘制步骤:

绘制背景 drawBackground(canvas)

绘制自己onDraw(canvas)

绘制前景,滚动条等装饰onDrawForeground(canvas) 

 

绘制自定义控件的步骤:

onMeasure  --> onLayout(自定义的是容器时需要重写该方法,自定义View时可不重写该方法) --> onDraw(可选,若容器里都是系统控件,可不重写)


3.4.1 绘制 源码分析,以FrameLayout为例

找到ViewRootlmpl中的performDraw方法:

private void performDraw() {
        if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
            return;
        } else if (mView == null) {
            return;
        }

        final boolean fullRedrawNeeded = mFullRedrawNeeded || mReportNextDraw;
        mFullRedrawNeeded = false;

        mIsDrawing = true;
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");

        boolean usingAsyncReport = false;
        if (mReportNextDraw && mAttachInfo.mThreadedRenderer != null
                && mAttachInfo.mThreadedRenderer.isEnabled()) {
            usingAsyncReport = true;
            mAttachInfo.mThreadedRenderer.setFrameCompleteCallback((long frameNr) -> {
                // TODO: Use the frame number
                pendingDrawFinished();
            });
        }

        try {
            boolean canUseAsync = draw(fullRedrawNeeded);
            if (usingAsyncReport && !canUseAsync) {
                mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
                usingAsyncReport = false;
            }
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }

        // For whatever reason we didn't create a HardwareRenderer, end any
        // hardware animations that are now dangling
        if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
            final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
            for (int i = 0; i < count; i++) {
                mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
            }
            mAttachInfo.mPendingAnimatingRenderNodes.clear();
        }

        if (mReportNextDraw) {
            mReportNextDraw = false;

            // if we're using multi-thread renderer, wait for the window frame draws
            if (mWindowDrawCountDown != null) {
                try {
                    mWindowDrawCountDown.await();
                } catch (InterruptedException e) {
                    Log.e(mTag, "Window redraw count down interrupted!");
                }
                mWindowDrawCountDown = null;
            }

            if (mAttachInfo.mThreadedRenderer != null) {
                mAttachInfo.mThreadedRenderer.setStopped(mStopped);
            }

            if (LOCAL_LOGV) {
                Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
            }

            if (mSurfaceHolder != null && mSurface.isValid()) {
                SurfaceCallbackHelper sch = new SurfaceCallbackHelper(this::postDrawFinished);
                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();

                sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
            } else if (!usingAsyncReport) {
                if (mAttachInfo.mThreadedRenderer != null) {
                    mAttachInfo.mThreadedRenderer.fence();
                }
                pendingDrawFinished();
            }
        }
    }

代码很多不用都看,找到其中的draw方法,点进去,draw()方法里代码也很多,不粘贴了,找到draw()方法里的drawSoftware方法,然后是drawSoftware方法中的mView.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)
...
...

可以看到,注释写的非常详细,已经把绘制的步骤一一列举出来了,省略的没有粘贴的代码就是一步步执行步骤的具体代码逻辑。

 

最后,来张神图:

 

 

参考文章

View的平滑移动:https://blog.csdn.net/itachi85/article/details/50724558

Android View体系:https://blog.csdn.net/itachi85/article/details/51577896

Android事件分发机制详解:https://juejin.im/post/5d3e5278e51d4556f76e8194#heading-18

View的工作流程:https://blog.csdn.net/qian520ao/article/details/78657084

 

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

许进进

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值