从点击App图标到View显示出来主要流程(三)源码解析View测量布局绘制流程

View测量、布局、绘制流程

在Activity启动时,执行AcitivtyThread.handleResumeActivity()方法时,会调用ActivityClientRecord.activity.makeVisible(),在方法是在执行Activity.onResume之后才执行的,从Activity.makeVisible()到View的测量、布局、绘制的流程如下:

ActivityThread.handleResumeActivity();
Activity.makeVisible();  //执行Activity.onResume之后,再执行makeVisible;
ViewManager.addView(DecorView...)//DecorView是根布局,后续会用到
WindowManagerImpl.addView();//ViewManager是一个接口,真正实现在WindowManagerImpl中;
WindowManagerGlobal.addView();//WindowManagerImple并没有实现WIndow三大操作,而是全部交给WindowManagerGlobal来处理;
ViewRootImpl.setView(view, wparams, panelParentView);// 将传进来的参数DecorView设置到root中。参数view就是DecorView
ViewRootImpl.requestLayout();
ViewRootImpl.scheduleTraversals();
ViewRootImpl.doTraversal();
ViewRootImpl.performTraversals();
ViewRootImpl.performMeasure()  performLayout()  performDraw();//在performTraversals中调用测量、布局、绘制操作;

WindowManagerGlobal.addView()方法:

WindowManagerGlobal
    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        // 1、检查参数是否合法
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (display == null) {
            throw new IllegalArgumentException("display must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }
        // 2、创建ViewRootImpl并将View添加到列表中。这里每次都会new一个ViewRootImpl对象,
        // 所以说调用一次addView,就会有一个ViewRootImpl,也可以理解为一个Activity就会创建一个ViewRootImpl
        ViewRootImpl root;
        View panelParentView = null;

            // 获得ViewRootImpl对象root
            // ViewRoot相当于是MVC模型中的Controller,它有以下职责:
            // 1. 负责为应用程序窗口视图创建Surface。
            // 2. 配合WindowManagerService来管理系统的应用程序窗口。
            // 3. 负责管理、布局和渲染应用程序窗口视图的UI。
            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            // addView时会将相关对象添加到对应集合中,存储这些ViewRootImpl, View, LayoutParam
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);

            // do this last because it fires off messages to start doing things
            try {
                // 3、通过ViewRootImpl来更新界面并显示在窗口上,完成Window的添加过程
                // 将传进来的参数DecorView设置到root中。参数view就是DecorView
                root.setView(view, wparams, panelParentView);
            } catch (RuntimeException e) {
            }
        }
    }

说明:
(1)参数view就是根View(DecorView);
(2)Window是以view的形式存在,Android中所有视图都是通过Window来呈现的,View是Android中视图呈现的方式;
(3)Window有三种类型:分别是应用Window(对应着一个Activity)、子Window(附属在特定Window之上,例如Dialog)和系统Window(Toast和系统状态栏);
(4)一个Activity对应一个Window,一个Window对应着一个ViewRootImpl,可以通过adb shell dumpsys meminfo 可以在Objects中看到Activity个数和ViewRootImpl个数;如下图所示:


从点击App图标到View显示出来主要流程(三)源码解析View测量布局绘制流程_第1张图片
Activity-ViewRootImpl.png

ViewRootImpl.setView()方法:

ViewRootImpl类:
    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                // 将顶层视图DecorView赋值给全局的mView,后续测量、布局、绘制都是从根View(mView)开始的
                mView = view;
                // 通过requestLayout来完成异步刷新请求,requestLayout最终会调用performTraversals方法来完成View的绘制
                requestLayout();
                if ((mWindowAttributes.inputFeatures
                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                    // 当窗口没有按键事件传输通道时,创建一个InputChannel对象,相当于一个管道,
                    // 其他进程通过该管道向窗口发送按键事件消息
                    mInputChannel = new InputChannel();
                }
                // 接着会通过WindowSession最终来完成Window的添加过程
                try {
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    // 2、调用mWindowSession添加View
                    // 通过Binder调用,进入system_server进程的Session.
                    // mWindowSession的类型是IWindowSession,它是一个Binder对象,
                    // 真正的实现类是Session,这也就是之前提到的IPC调用的位置。
                    // 在Session内部会通过WindowManagerService来实现Window的添加
                    // WMS与APP交互的接口通过WindowState的IWindow
                    // mInputChannel:待注册的管道对象
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
                }

                if (mInputChannel != null) {
                    if (mInputQueueCallback != null) {
                        mInputQueue = new InputQueue();
                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
                    }
                    // 输入事件从Native传到Java层最先调用WindowInputReceiver.onInputEvent()方法
                    mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
                            Looper.myLooper());
                }
            }
        }
    }

相关方法调用顺序为:requestLayout()>scheduleTraversals()>doTraversal(),其中doTraversal会调用到ViewRootImpl.performTraversals()方法,在performTraversals()方法开始View的测量、布局、绘制工作;measure过程决定了View的宽高、Measure完之后,可以通过getMeasureWidth和getMeasureHeight获取View的测量宽高,几乎所有情况它们都等于View的最终宽高;Layout过程决定了View的四个顶点坐标和实际的View的宽高,可以通过getTop、getBottom、getLeft、getRight得到View的四个顶点位置,通过getWidth、getHeigt获取View的最终宽高,Draw过程决定了View的显示,只有draw完成之后View的内容才会显示在屏幕上。

ViewRootImpl类:
    private void performTraversals() {
        // cache mView since it is used so much below...
        // mView就是DecorView根布局
        final View host = mView;
        if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                updatedConfiguration) {
            // 根据Activity窗口的当前宽(高)度和宽(高)度测量规范来计算得到它的顶层视图DecorView
            // 的宽度测量规范childWidthMeasureSpec和高度测量规范childHeightMeasureSpec。
            // mWidth和mHeight表示窗口的宽高,lp.width和lp.height表示DecorView根布局宽和高,
            // 在创建ViewGroup实例时等于MATCH_PARENT
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
            int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
            // 执行测量操作
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
        // 执行布局操作
        performLayout(lp, mWidth, mHeight);
        // 执行绘制操作
        performDraw();
    }

理解MeasureSpec
(1)View.MeasureSpec:32位int值,高两位SpecMode(测量模式),低30位SpecSize(测量值);系统通过MeasureSpec对View进行测量;
(2)测量模式有三种:
UNSPECIFIED:未指定模式,View想多大就多大,父容器不做限制,一般用于系统内部的测量。
AT_MOST:最大模式,父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体是什么值要看不同View的具体实现,他对应于LayoutParams中的wrap_content;
EXACTLY:精确模式,父容器已经检测出View所需的精确大小,这时候VIew的最终大小就是SpecSize所指定的值,它对应于LayoutParams中的match_parent和具体的数值两种模式;
(3)MeasureSpec由View的layoutParams和父容器一起决定;根View(DecorVIew)和普通View有区别:DecorView由窗口尺寸和其自身的layoutParams决定;普通View由父容器和自身layoutParams来决定;确定MeasureSpec就知道View的测量大小;
(4)DecorView创建过程在ViewRootImple的measureHieraychy中调用getRootMeasureSpec(desiredWindowWidth, lp.width),其中desiredWindowWidth是当前Window的大小(向上追代码可以确定就是Window的大小),lp.width是DecorView的layoutParams中的宽度;(lp.width从onresume的wm.addView方法开始将该DecorView的参数传递下来),这样DecorView的MeasureSpec就确定下来了。

ViewRootImpl类:
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

            //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满整个屏幕
            case ViewGroup.LayoutParams.MATCH_PARENT:
                // Window can't resize. Force root view to be windowSize.
                measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
                break;
            //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满整个屏幕
            case ViewGroup.LayoutParams.WRAP_CONTENT:
                // Window can resize. Set max size for root view.
                measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
                break;
            //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小
            default:
                // Window wants to be an exact size. Force root view to be that size.
                measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
                break;
        }
        return measureSpec;
    }

(5)普通View的MeasureSpec:最终会调用到ViewGroup.measuresChildWIthMargins(),然后调用
getChildMeasureSpec(spec,padding,childDimens)其中padding是父容器已经占用的空间,ViewGroup.measuresChildWIthMargins()方法如下:

ViewGroup类:
    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
        //父View是精确模式
        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);
    }

通过以上源码可以得到表中的结论;


从点击App图标到View显示出来主要流程(三)源码解析View测量布局绘制流程_第2张图片
普通View的MeasureSpec创建规则.png

通过上表可以看出,只要提供父容器的MeasureSpec和子元素的LayoutParams,就可以快速确定出子元素的MeasureSpec,有了MeasureSpec就可以确定出子View的测量后的大小。
View的工作过程:主要是指View的测量、布局、绘制三大流程,这三大流程都从从根View(DecorView)开始的。measure确定view的宽高、layout确定view的最终宽高和四个顶点位置、draw将View绘制到屏幕上。
测量过程
对于原始View,通过measure方法就完成了其测量过程;但是对于ViewGroup除了完成自己的测量过程外,还会遍历去调用所有子元素的measure方法,各个子元素再递归去执行measure流程;
View的measure过程
View的测量是从根View(DecorView)开始的,在ViewRootImpl.performTraversals()方法中调用performMeasure开始View的测量流程

ViewRootImpl类:
    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就是DecorView,在setViews方法中会将DecorView赋值给mView;继续执行mView.measure()方法

View类:
    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        if (forceLayout || needsLayout) {
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                // 调用了onMeasure方法进行测量,说明View主要的测量逻辑是在该方法中实现。
                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;
            }
        }
    }

View的measure方法是final类型,所以无法重写,在measure中会调用onmeasure,onmeasure方法可以重写,会继续执行DecorView的onMeasure,在DecorView中会调用super.onMeasure,由于DecorView继承Framelayou,所以会继续执行FrameLayout.onMeasure方法;下一步我们在分析ViewGroup.onMeasure;我们先继续分析View.onMeasure方法;

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

在View.onMeasure中会调用setMeasureDimension方法设置View的测量宽高,我们只需要看getDefaultSize即可

View类:
    public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        //获得测量模式
        int specMode = MeasureSpec.getMode(measureSpec);
        //获得父亲容器留给子视图View的大小
        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;
    }

getDefaultSize根据View布局设置的宽高和父View传递的测量规格MeasureSpec计算出View的测量宽高。我们只要看AT_MOST和EXACTLY这两种情况,这两种情况的返回大致就是MeasureSpec中的specSize值,这个specSize就是View测量后的大小。
View测量过程主要工作:根据View的MeasureSpec得到View的测量大小,然后调用setMeasureDimension设置view的测量宽高,并且测量工作最先从根View(DecorView)开始;
ViewGroup measure过程
对于ViewGroup的measure过程除了完成自己的Measure过程,还需要遍历去调用所有子元素的measure方法,各个子元素再递归执行这个过程。在View的测量过程中我们已经从DecorView.measure方法开始执行到了FrameLayout.onMeasure,我们继续来看ViewGroup的onMeasure方法;

FrameLayout类:
    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) {
                //测量FrameLayout下每个子视图View的宽和高
                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);
                    }
                }
            }
        }

        //设置当前FrameLayout测量结果,此方法的调用表示当前View测量的结束
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));
    }

在FrameLayout.onMeasure中会调用measureChildWithMargins方法去遍历调用每个子元素的Measure方法,这样各个子元素的就进入了Measure过程,在子元素测量完毕后,会根据子元素的情况来测量自己的大小。调用resolveSizeAndState来获取自身的测量宽高。
ViewGroup.measureChildWithMargins方法如下:

ViewGroup类:
    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);
    }

在该方法中主要子View做了两件事,首先根据父View的MeasureSpec和自身的布局参数得到子View的MeasureSpec,然后调用子VIew自己的Measure方法;这样一个个子View就完成了测量过程;
View的测量过程是三大流程中最复杂的一个,measure测量完成后,就可以获取到View的测量宽高,在某些极端情况下,系统需要多次测量才可能确定最终的测量宽高,这种情况下onMeasure中拿到的宽高很可能不准确,最好是在onLayout总去获取View的测量宽高。同时在oncreate、onstart、onresume获取不到准确的测量宽高,因为View的测量流程是在onResume之后。
以上介绍了ViewRootImpl.performTraversals中performMeasure方法,在performMeasure中首先从根View(DecorView)开始执行Measure过程,然后分别介绍了View和ViewGroup的测量过程。
布局过程
Layout过程从ViewRootImpl.performTraversals中的performLayout方法开始,即从DecorView开始。Layout作用是ViewGroup用来确定子View的位置,当ViewGroup位置被确定之后,再onLayout中遍历所以自己元素,并调用其Layout方法,在layout方法中onLayout又会被调用,layout过程和Measure过程相比比较简单,layout方法确定View自身的位置,onLayout确定所有子View的位置。我们从看ViewRootImpl.performLayout方法:

ViewRootImpl类:
    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
                               int desiredWindowHeight) {
        // mView就是DecorView
        final View host = mView;
        try {
            // DecorView请求布局。DecorView的四个位置左=0,顶=0,右=屏幕宽,底=屏幕高,说明DecorView布局的位置是从
            // 屏幕最左最顶端开始布局,到屏幕最低最右结束。因此DecorView根布局是充满整个屏幕的
            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
            ...
        }
        mInLayout = false;
    }

mView就是DecorView,host.layout方法会调用View.layout方法;

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

        //保存上一次View的四个位置
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        //如果布局有改变,条件成立,则视图View重新布局
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //调用onLayout,将具体布局逻辑留给子类实现
            onLayout(changed, l, t, r, b);
        }
        ...
    }

在layout方法中会调用setFrame方法来设置View的四个顶点位置,即初始化mLeft、mRight、mTop、mBottom.View的四个顶点确定之后那么在父容器中的位置就确定了。接着调用onLayou方法,在该方法中确定子元素的位置。我们接着来看FrameLayout.onLayout方法;

FrameLayout类:
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //给子视图View进行布局
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

    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();

        //遍历当前FrameLayout下的子View
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            //当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                //获得子视图View的宽高
                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;

                //以下代码获得子视图View的四个位置,用于子视图View布局
                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);
            }
        }
    }

其中,当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的。
在ViewRootImpl.performlayou方法中首先调用DecorView的layou方法确定DecorView自身的位置,然后再调用DeocrView的onLayout方法所以子元素的位置。
绘制过程
Draw过程比较简单,它的作用是将View绘制到屏幕上。Draw过程从ViewRootImpl.performTraversals中的performDraw方法开始,即从DecorView开始。从performDraw到DecorView.draw方法流程如下:

ViewRootImpl.performDraw();
ViewRootImple.Draw();
DecorView.draw();
View.Draw();

在ViewRootImpl.draw方法中会调用mView.draw(),mView就是DecorView;我们来看View.draw方法:

    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)
         *      1.绘制当前视图的背景
         *      2.保存当前画布的堆栈状态,并且在当前画布上创建额外的图层,以便在Step5绘制当前视图在滑动时的边框渐变效果
         *      3.绘制当前视图的内容
         *      4.绘制当前视图的子视图的内容
         *      5.绘制当前视图在滑动时的边框渐变效果
         *      6.绘制当前视图的滚动条。
         */

        // Step 1, draw the background, if needed
        // Step1:绘制视图View的背景
        if (!dirtyOpaque) {
            drawBackground(canvas);
        }
    // Step 3, draw the content 绘制自己
    if (!dirtyOpaque) onDraw(canvas);
    // Step 4, draw the children 调用diapatchDraw绘制子元素
        dispatchDraw(canvas);
        // Step 6, draw decorations (foreground, scrollbars)
        onDrawForeground(canvas);
    }

View.onDraw主要工作:调用drawBackground(canvas)绘制自己的背景,
调用onDraw绘制自己;调用dipatchDraw绘制所有子元素;绘制装饰等等;View的绘制传递是通过dispatchDraw来实现的,dispatchDraw会遍历调用所有子元素的Draw,这样draw一层层的传递下去,最终完成所有View的绘制;
View测量、布局、绘制流程总结
View的测量布局绘制工作是从ViewRootImpl.performTraversals方法开始,分别调用调用performMeasure、performLayout、performDraw方法开始测量布局绘制工作,测量布局绘制工作都是从根View(DecorView)开始,然后一层层传递下去,最终完成所有View测量布局绘制工作;

你可能感兴趣的:(从点击App图标到View显示出来主要流程(三)源码解析View测量布局绘制流程)