从ViewRootImpl类分析View绘制的流程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从ViewRootImpl类分析View绘制的流程相关的知识,希望对你有一定的参考价值。

【出处:从ViewRootImpl类分析View绘制的流程 CSDN 废墟的树】

从上两篇博客 《从setContentView方法分析Android加载布局流程》 和 《从LayoutInflater分析XML布局解析成View的树形结构的过程》 中我们了解到Activity视图UI是怎么添加到Activity的根布局DecorView上面的。

我们知道Activity中的PhoneView对象帮我们创建了一个PhoneView内部类DecorView(父类为FrameLayout)窗口顶层视图,

然后通过LayoutInflater将xml内容布局解析成View树形结构添加到DecorView顶层视图中id为content的FrameLayout父容器上面。到此,我们已经知道Activity的content内容布局最终

会添加到DecorView窗口顶层视图上面,相信很多人也会有这样的疑惑:窗口顶层视图DecorView是怎么绘制到我们的手机屏幕上的呢?

这篇博客来尝试着分析DecorView的绘制流程。

技术分享

顶层视图DecorView添加到窗口的过程

DecorView是怎么添加到窗口的呢?这时候我们不得不从Activity是怎么启动的说起,当Activity初始化 Window和将布局添加到

PhoneWindow的内部类DecorView类之后,ActivityThread类会调用handleResumeActivity方法将顶层视图DecorView添加到PhoneWindow窗口,来看看handlerResumeActivity方法的实现:

0-1

Step1

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {

            ..................

            if (r.window == null && !a.mFinished && willBeVisible) {
                //获得当前Activity的PhoneWindow对象
                r.window = r.activity.getWindow();
                //获得当前phoneWindow内部类DecorView对象
                View decor = r.window.getDecorView();
                //设置窗口顶层视图DecorView可见度
                decor.setVisibility(View.INVISIBLE);
                //得当当前Activity的WindowManagerImpl对象
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (a.mVisibleFromClient) {
                    //标记根布局DecorView已经添加到窗口
                    a.mWindowAdded = true;
                    //将根布局DecorView添加到当前Activity的窗口上面
                    wm.addView(decor, l);

            .....................

分析:详细步骤以上代码都有详细注释,这里就不一一解释。handlerResumeActivity()方法主要就是通过第 23 行代码将

Activity的顶层视图DecorView添加到窗口视图上。我们来看看WindowManagerImpl类的addView()方法。

@Override
    public void addView(View view, ViewGroup.LayoutParams params) {
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

源码很简单,直接调用了 mGlobal对象的addView()方法。继续跟踪,mGlobal对象是WindowManagerGlobal类。进入WindowManagerGlobal类看addView()方法。

0-2

Step2

 public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {

        ............

        ViewRootImpl root;
        View panelParentView = null;

        ............

        //获得ViewRootImpl对象root
         root = new ViewRootImpl(view.getContext(), display);

        ...........

        // do this last because it fires off messages to start doing things
        try {
            //将传进来的参数DecorView设置到root中
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
          ...........
        }
    }

 

该方法中创建了一个ViewRootImpl对象root,然后调用ViewRootImpl类中的setView成员方法()。继续跟踪代码进入ViewRootImpl类分析:

0-3

Step3

 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
            //将顶层视图DecorView赋值给全局的mView
                mView = view;
            .............
            //标记已添加DecorView
             mAdded = true;
            .............
            //请求布局
            requestLayout();

            .............     
        }
 }

 

该方法实现有点长,我省略了其他代码,直接看以上几行代码:

  1. 将外部参数DecorView赋值给mView成员变量
  2. 标记DecorView已添加到ViewRootImpl
  3. 调用requestLayout方法请求布局

0-4

跟踪代码进入到 requestLayout()方法: 
Step4

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
    ................

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
        }
    }

..............

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

...............

 void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);

            try {
                performTraversals();
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
        }
    }

............

 

跟踪代码,最后DecorView的绘制会进入到ViewRootImpl类中的performTraversals()成员方法,这个过程可以参考上面的代码流程图。现在我们主要来分析下 ViewRootImpl类中的performTraversals()方法。

0-5

Step5

private void performTraversals() {
        // cache mView since it is used so much below...
        //我们在Step3知道,mView就是DecorView根布局
        final View host = mView;
        //在Step3 成员变量mAdded赋值为true,因此条件不成立
        if (host == null || !mAdded)
            return;
        //是否正在遍历
        mIsInTraversal = true;
        //是否马上绘制View
        mWillDrawSoon = true;

        .............
        //顶层视图DecorView所需要窗口的宽度和高度
        int desiredWindowWidth;
        int desiredWindowHeight;

        .....................
        //在构造方法中mFirst已经设置为true,表示是否是第一次绘制DecorView
        if (mFirst) {
            mFullRedrawNeeded = true;
            mLayoutRequested = true;
            //如果窗口的类型是有状态栏的,那么顶层视图DecorView所需要窗口的宽度和高度就是除了状态栏
            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
                    || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
                // NOTE -- system code, won‘t try to do compat mode.
                Point size = new Point();
                mDisplay.getRealSize(size);
                desiredWindowWidth = size.x;
                desiredWindowHeight = size.y;
            } else {//否则顶层视图DecorView所需要窗口的宽度和高度就是整个屏幕的宽高
                DisplayMetrics packageMetrics =
                    mView.getContext().getResources().getDisplayMetrics();
                desiredWindowWidth = packageMetrics.widthPixels;
                desiredWindowHeight = packageMetrics.heightPixels;
            }
    }
............
//获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示DecorView根布局宽和高
 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

  // Ask host how big it wants to be
  //执行测量操作
  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

........................
//执行布局操作
 performLayout(lp, desiredWindowWidth, desiredWindowHeight);

.......................
//执行绘制操作
performDraw();

}

 

该方法主要流程就体现了View绘制渲染的三个主要步骤,分别是测量,布局,绘制三个阶段。

技术分享

这里先给出android系统View的绘制流程:依次执行View类里面的如下三个方法:

  1. measure(int ,int) :测量View的大小
  2. layout(int ,int ,int ,int) :设置子View的位置
  3. draw(Canvas) :绘制View内容到Canvas画布上

测量measure

1-1

从performTraversals方法我们可以看到,在执行performMeasure测量之前要通过getRootMeasureSpec方法获得顶层视图DecorView的测量规格,跟踪代码进入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) {
        //匹配父容器时,测量模式为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;
    }

 

分析:该方法主要作用是在整个窗口的基础上计算出root view(顶层视图DecorView)的测量规格,该方法的两个参数分别表示:

  1. windowSize:当前手机窗口的有效宽和高,一般都是除了通知栏的屏幕宽和高
  2. rootDimension 根布局DecorView请求的宽和高,由前面的博客我们知道是MATCH_PARENT

由 《从setContentView方法分析Android加载布局流程》可知,我们的DecorView根布局宽和高都是MATCH_PARENT,

因此DecorView根布局的测量模式就是MeasureSpec.EXACTLY,测量大小一般都是整个屏幕大小,所以一般我们的Activity

窗口都是全屏的。因此上面代码走第一个分支,通过调用MeasureSpec.makeMeasureSpec方法将

DecorView的测量模式和测量大小封装成DecorView的测量规格。

1-2

由于performMeasure()方法调用了 View中measure()方法俩进行测量,并且DecorView(继承自FrameLayout)的父类是

ViewGroup,祖父类是View。因此我们从View的成员函数measure开始分析整个测量过程。

技术分享

这个过程分为 3 步,我们来一一分析。

Step1


    int mOldWidthMeasureSpec = Integer.MIN_VALUE;

    int mOldHeightMeasureSpec = Integer.MIN_VALUE;

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

        ..................
        //如果上一次的测量规格和这次不一样,则条件满足,重新测量视图View的大小
        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                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;
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

    }

 

分析: 
1.代码第10行:判断当前视图View是否需要重新测量,当上一次视图View测量的规格和本次视图View测量规格不一样时,就说明视图View的大小有改变,因此需要重新测量。

2.代码第23行:调用了onMeasure方法进行测量,说明View主要的测量逻辑是在该方法中实现。

3.代码第35-36行:保存本次视图View的测量规格到mOldWidthMeasureSpec和mOldHeightMeasureSpec以便下次测量条件的判断是否需要重新测量。

1-3

跟踪代码,进入View类的 onMeasure方法

 /**
     * <p>
     * Measure the view and its content to determine the measured width and the
     * measured height. This method is invoked by {@link #measure(int, int)} and
     * should be overriden by subclasses to provide accurate and efficient
     * measurement of their contents.
     * </p>
     *
     * <p>
     * <strong>CONTRACT:</strong> When overriding this method, you
     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
     * measured width and height of this view. Failure to do so will trigger an
     * <code>IllegalStateException</code>, thrown by
     * {@link #measure(int, int)}. Calling the superclass‘
     * {@link #onMeasure(int, int)} is a valid use.
     * </p>
     *
     * <p>
     * The base class implementation of measure defaults to the background size,
     * unless a larger size is allowed by the MeasureSpec. Subclasses should
     * override {@link #onMeasure(int, int)} to provide better measurements of
     * their content.
     * </p>
     *
     * <p>
     * If this method is overridden, it is the subclass‘s responsibility to make
     * sure the measured height and width are at least the view‘s minimum height
     * and width ({@link #getSuggestedMinimumHeight()} and
     * {@link #getSuggestedMinimumWidth()}).
     * </p>
     *
     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     *
     * @see #getMeasuredWidth()
     * @see #getMeasuredHeight()
     * @see #setMeasuredDimension(int, int)
     * @see #getSuggestedMinimumHeight()
     * @see #getSuggestedMinimumWidth()
     * @see android.view.View.MeasureSpec#getMode(int)
     * @see android.view.View.MeasureSpec#getSize(int)
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

 

分析: 
该方法的实现也很简单,直接调用setMeasuredDimension方法完成视图View的测量。我们知道,Android中所有的视图组件都是继承自View实现的。因此该方法提供了一个默认测量视图View大小的实现。

1-4

言外之意,如果你不想你自己的View使用默认实现来测量View的宽高的话,你可以在子类中重写onMeasure方法来自定义测量方法。我们先来看看默认测量宽高的实现。跟踪代码进入getDefaultSize方法:

 /**
     * Utility to return a default size. Uses the supplied size if the
     * MeasureSpec imposed no constraints. Will get larger if allowed
     * by the MeasureSpec.
     *
     * @param size Default size for this view
     * @param measureSpec Constraints imposed by the parent
     * @return The size this view should be.
     */
    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;
    }

 

分析:该方法的作用是根据View布局设置的宽高和父View传递的测量规格重新计算View的测量宽高。由此可以知道,我们布局的

子View最终的大小是由布局大小和父容器的测量规格共同决定的。如果自定义View你没有重写onMeasure使用系统默认方法的

话,测量模式MeasureSpec.AT_MOST和MeasureSpec.EXACTLY下的测量大小是一样的。我们来总结一下测量模式的种类:

  1. MeasureSpec.EXACTLY:确定模式,父容器希望子视图View的大小是固定,也就是specSize大小。
  2. MeasureSpec.AT_MOST:最大模式,父容器希望子视图View的大小不超过父容器希望的大小,也就是不超过specSize大小。
  3. MeasureSpec.UNSPECIFIED: 不确定模式,子视图View请求多大就是多大,父容器不限制其大小范围,也就是size大小。

从上面代码可以看出,当测量模式是MeasureSpec.UNSPECIFIED时,View的测量值为size,当测量模式为

MeasureSpec.AT_MOST或者case MeasureSpec.EXACTLY时,View的测量值为specSize。我们知道,specSize是由父容器决

定,那么size是怎么计算出来的呢?getDefaultSize方法的第一个参数是调用getSuggestedMinimumWidth方法获得。进入getSuggestedMinimumWidth方法看看实现:

/**
     * Returns the suggested minimum width that the view should use. This
     * returns the maximum of the view‘s minimum width)
     * and the background‘s minimum width
     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
     * <p>
     * When being used in {@link #onMeasure(int, int)}, the caller should still
     * ensure the returned width is within the requirements of the parent.
     *
     * @return The suggested minimum width of the view.
     */
    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

 

原来size大小是获取View属性当中的最小值,也就是 android:minWidth和 android:minHeight的值,前提是View没有设置背景属性。否则就在最小值和背景的最小值中间取最大值。

sizeSpec大小是有父容器决定的,我们由 1-1节知道父容器DecorView的测量模式是MeasureSpec.EXACTLY,测量大小sizeSpec是整个屏幕的大小。

setp2 
而DecorView是继承自FrameLayout的,那么我们来看看FrameLayout类中的onMeasure方法的实现

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        ..............
        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);
                    }
                }
            }
        }

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

 

分析:由以上代码发现,ViewGroup测量结果都是带边距的,代码第9-27行就是遍历测量FrameLayout下子视图View的大小了。

代码第44行,最后调用setMeasuredDimension方法设置当前View的测量结果,此方法的调用表示当前View测量结束。

那么我们来分析下代码第12行measureChildWithMargins方法测量FrameLayout下的子视图View的大小,跟踪源码:

Step3: 
由于FrameLayout父类是ViewGroup,measureChildWithMargins方法在ViewGroup下

/**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding
     * and margins. The child must have MarginLayoutParams The heavy lifting is
     * done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param widthUsed Extra space that has been used up by the parent
     *        horizontally (possibly by other children of the parent)
     * @param parentHeightMeasureSpec The height requirements for this view
     * @param heightUsed Extra space that has been used up by the parent
     *        vertically (possibly by other children of the parent)
     */
    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);
    }

 

分析:该方法中调用getChildMeasureSpec方法来获得ViewGroup下的子视图View的测量规格。然后将测量规格最为参数传递给

View的measure方法,最终完成所有子视图View的测量。来看看这里是怎么获得子视图View的测量规格的,进入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;

       ...........

        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

 

分析:由1-1节我们知道根布局DecorView的测量规格中的测量模式是MeasureSpec.EXACTLY,测量大小是整个窗口大小。因此上面代码分支走MeasureSpec.EXACTLY。子视图View的测量规格由其宽和高参数决定。

  1. 当DecorView根布局的子视图View宽高为一个确定值childDimension时,该View的测量模式为MeasureSpec.EXACTLY,测量大小就是childDimension。
  2. 当子视图View宽高为MATCH_PARENT时,该View的测量模式为MeasureSpec.EXACTLY,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。
  3. 当子视图View宽高为WRAP_CONTENT时,该View的测量模式为MeasureSpec.AT_MOST,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。

这里我们来验证一下以上的结论,目的是进一步理解 View的几种测量模式和View的测量规格。

1.定义一个布局activity_main.xml如下:

<com.xjp.layoutdemo.MyView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:gravity="start"/>

这个布局很简单,直接将自定义的MyView作为Activity的内容布局。 


2.自定义MyView代码如下:

public class MyView extends View {

    private static final String TAG = "MyCustomView";
    private String titleText = "Hello world";

    private int titleColor = Color.BLACK;
    private int titleBackgroundColor = Color.RED;
    private int titleSize = 16;

    private Paint mPaint;
    private Rect mBound;

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                Log.e(TAG, "UNSPECIFIED.....");
                break;
            case MeasureSpec.AT_MOST:
                Log.e(TAG, "AT_MOST.....");
                break;
            case MeasureSpec.EXACTLY:
                Log.e(TAG, "EXACTLY.....");
                break;
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 初始化
     */
    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(titleSize);
        /**
         * 得到自定义View的titleText内容的宽和高
         */
        mBound = new Rect();
        mPaint.getTextBounds(titleText, 0, titleText.length(), mBound);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(titleBackgroundColor);
        canvas.drawCircle(getWidth() / 2f, getWidth() / 2f, getWidth() / 2f, mPaint);
        mPaint.setColor(titleColor);
        canvas.drawText(titleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
    }
}

 

 

技术分享 
自定义的MyView也很简单,仅仅重写了onDraw方法,onMeasure方法调用父类方法。代码运行之后你会发现,

1.布局中设置的MyView大小是wrap_content包裹内容的,但是View视图却充满整个屏幕。看打印发现当前的测量模式是MeasureSpec.AT_MOST。

2.当MyView大小是match_parent填满父容器时,View视图也是充满整个屏幕,看打印发现测量模式是MeasureSpec.EXACTLY。

3.当MyView大小是固定值,比如是1200dp和1200dp时,View视图是超出整个屏幕的。 
技术分享

原因是此处的Activity内容布局的父容器也是一个id为content的FrameLayout布局。这里就不解释以上三种情况的原因了,参考Stpe3解释的很详细了。

至此,整个View树型结构的布局测量流程可以归纳如下:

技术分享

measure总结

    1. View的measure方法是final类型的,子类不可以重写,子类可以通过重写onMeasure方法来测量自己的大小,当然也可以不重写onMeasure方法使用系统默认测量大小。
    2. View测量结束的标志是调用了View类中的setMeasuredDimension成员方法,言外之意是,如果你需要在自定义的View中重写onMeasure方法,在你测量结束之前你必须调用setMeasuredDimension方法测量才有效。
    3. 在Activity生命周期onCreate和onResume方法中调用View.getWidth()和View.getMeasuredHeight()返回值为0的,是因为当前View的测量还没有开始,这里关系到Activity启动过程,文章开头说了当ActivityThread类中的performResumeActivity方法执行之后才将DecorView添加到PhoneWindow窗口上,开始测量。在Activity生命周期onCreate在中performResumeActivity还为执行,因此调用View.getMeasuredHeight()返回值为0。
    4. 子视图View的大小是由父容器View和子视图View布局共同决定的。

以上是关于从ViewRootImpl类分析View绘制的流程的主要内容,如果未能解决你的问题,请参考以下文章

android View绘制源码分析

Android UI绘制之View绘制的工作原理

Android ViewRootImpl

View绘制流程(一)

2.View绘制分析笔记之onMeasure

Android View 绘制流程(Draw) 完全解析