从ViewRootImpl类分析View绘制的流程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/feidu804677682/article/details/46772477

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

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

我们知道Activity中的PhoneWindow对象帮我们创建了一个PhoneWindow内部类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布局共同决定的。

布局Layout

0-5节可知,View视图绘制流程中的布局layout是由ViewRootImpl中的performLayout成员方法开始的,看源码:

2-1

 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        ..................
        //标记当前开始布局
        mInLayout = true;
        //mView就是DecorView
        final View host = mView;
        ..................
        //DecorView请求布局
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        //标记布局结束
        mInLayout = false;
        ..................
}

分析:
代码第10行发现,DecorView的四个位置左=0,顶=0,右=屏幕宽,底=屏幕宽,说明DecorView布局的位置是从屏幕最左最顶端开始布局,到屏幕最低最右结束。因此DecorView根布局是充满整个屏幕的。

该方法主要调用了View类的layout方法,跟踪代码进入View类的layout方法瞧瞧吧

2-2

/**
     * Assign a size and position to a view and all of its
     * descendants
     *
     * <p>This is the second phase of the layout mechanism.
     * (The first is measuring). In this phase, each parent calls
     * layout on all of its children to position them.
     * This is typically done using the child measurements
     * that were stored in the measure pass().</p>
     *
     * <p>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.</p>
     *
     * @param l Left position, relative to parent
     * @param t Top position, relative to parent
     * @param r Right position, relative to parent
     * @param b Bottom position, relative to parent
     */
    @SuppressWarnings({"unchecked"})
    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);
            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;
    }

分析:
1.代码第23-32行保存本次布局的四个位置,用于布局变化的监听事件,如果用户设置了布局变化的监听事件,则代码第43-50就会执行设置监听事件。

2.代码第34-35行设置当前View的布局位置,也就是当调用了setFrame(l, t, r, b)方法之后,当前View布局基本完成,既然这样为什么还要第39行 onLayout方法呢?稍后解答,这里来分析一下setFrame是怎么设置当前View的布局位置的。

进入setFrame方法

2-3

/**
     * Assign a size and position to this view.
     *
     * This is called from layout.
     *
     * @param left Left position, relative to parent
     * @param top Top position, relative to parent
     * @param right Right position, relative to parent
     * @param bottom Bottom position, relative to parent
     * @return true if the new size and position are different than the
     *         previous ones
     * {@hide}
     */
    protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
        //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;

            // Remember our drawn bit
            int drawn = mPrivateFlags & PFLAG_DRAWN;
            //得到本次和上次的宽和高
            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            //判断本次View的宽高和上次View的宽高是否相等
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

            // Invalidate our old position
            //清楚上次布局的位置
            invalidate(sizeChanged);
            //保存当前View的最新位置
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

            mPrivateFlags |= PFLAG_HAS_BOUNDS;

            //如果当前View的尺寸有所变化
            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }

            ...............
        return changed;
    }

分析:
1.代码第17行,如果当前View视图的最新位置和上一次不一样时,则View会重新布局。

2.代码第32-38行,保存当前View的最新位置,到此当前View的布局基本结束。从这里我们可以看到,四个全局变量 mLeft,mTop,mRight,mBottom在此刻赋值,联想我们平时使用的View.getWidth()方法获得View的宽高,你可以发现,其实View.getWidth()方法的实现如下:

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

也就是说,以上两个方法是获得View布局时候的宽高,因此,我们只有在View 布局完之后调用getWidth才能真正获取到大于0的值。

2-4

细心的你会发现,既然2-3小节调用了setFrame方法,也就是当前View的布局结束了,那么View中的onLayout方法又是干嘛的呢?进入onLayout方法:

/**
     * Called from layout when this view should
     * assign a size and position to each of its children.
     *
     * Derived classes with children should override
     * this method and call layout on each of
     * their children.
     * @param changed This is a new size or position for this view
     * @param left Left position, relative to parent
     * @param top Top position, relative to parent
     * @param right Right position, relative to parent
     * @param bottom Bottom position, relative to parent
     */
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

分析:原来这是一个空方法,既然是空方法,那么该方法的实现应该在子类中。前面分析过,DecorView是继承自FrameLayout的,那么进入FarmeLayout类中看看 onLayout方法的实现吧:

  * {@inheritDoc}
     */
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        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();

        mForegroundBoundsChanged = true;
        //遍历当前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);
            }
        }
    }

分析:在FrameLayout中的onLayout方法中仅仅是调用了layoutChildren方法,从该方法名称我们不难看出,原来该方法的作用是

给子视图View进行布局的。也就是说FrameLayout布局其实在View类中的layout方法中已经实现,布局的逻辑实现是在父视图中

实现的,不像View视图的measure测量,通过子类实现onMeasure方法来实现测量逻辑。

1.代码第20-71行,遍历获得FrameLayout的子视图View的四个位置,然后调用child.layout对子视图View进行布局操作。

2.代码第23行,对每个子视图View的可见度进行了判断,如果当前子视图View可见度类型为GONE,则当前子视图View不进行布局,这也就是为什么可见度GONE类型时是不占据屏幕空间的,而其他两种VISIBLE和INVISIBLE是占据屏幕空间的。

2-5

由于FrameLayout类是继承自ViewGroup类的,那么我们进入ViewGroup类去窥探一下onLayout方法具体做了什么?

/**
     * {@inheritDoc}
     */
    @Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

你会惊讶的发现,在ViewGroup类中的onLayout方法居然是一个抽象方法,现在你明白了吧?我们的FrameLayout继承自ViewGroup,自然FrameLayout就必须实现ViewGroup中的抽象方法onLayout,而FrameLyayout中的onLayout方法的作用是用来设置它的子视图View的布局位置。

到此,我们的布局流程可以用如下图表示:

这里写图片描述

layout布局总结

1.视图View的布局逻辑是由父View,也就是ViewGroup容器布局来实现的。因此,我们如果自定义View一般都无需重写onMeasure方法,但是如果自定义一个ViewGroup容器的话,就必须实现onLayout方法,因为该方法在ViewGroup是抽象的,所有ViewGroup的所有子类必须实现onLayout方法。

2.当我们的视图View在布局中使用 android:visibility=”gone” 属性时,是不占据屏幕空间的,因为在布局时ViewGroup会遍历每个子视图View,判断当前子视图View是否设置了 Visibility==GONE,如果设置了,当前子视图View就会添加到父容器上,因此也就不占据屏幕空间。具体可以参考2-4节。

3.必须在View布局完之后调用getHeight()和getWidth()方法获取到的View的宽高才大于0。具体可以参考2-3节。

View的绘制Draw

0-5节可知,View视图绘制流程中的最后一步绘制draw是由ViewRootImpl中的performDraw成员方法开始的,跟踪代码,最后会在ViewRootImpl类中的drawSoftware方法绘制View:

3-1

  private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {

        // Draw with software renderer.
        final Canvas canvas;
        try {
            //从surface对象中获得canvas变量
            canvas = mSurface.lockCanvas(dirty);

            // If this bitmap's format includes an alpha channel, we
            // need to clear it before drawing so that the child will
            // properly re-composite its drawing on a transparent
            // background. This automatically respects the clip/dirty region
            // or
            // If we are applying an offset, we need to clear the area
            // where the offset doesn't appear to avoid having garbage
            // left in the blank areas.
            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
            }

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

            try {
                //调整画布的位置
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;
                //调用View类中的成员方法draw开始绘制View视图
                mView.draw(canvas);
            } 

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

        return true;
    }

分析:代码第8行,从mSurface对象中获得canvas画布,然后将变量canvas变量作为参数传递给第33行代码中的draw方法。由此

可知,我们的视图View最终是绘制到Surface中去的,关于Surface相关的知识,可以参考这篇大神的博客:

Android应用程序窗口(Activity)的绘图表面(Surface)的创建过程分析

跟踪代码,进入View的draw方法分析源码:

3-2

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

            // Step 6, draw decorations (scrollbars)
            onDrawScrollBars(canvas);

            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // we're done...
            return;
        }

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

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

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }
    }

分析:
从代码第7-17行可知,视图View的绘制可以分为如下6个步骤:

这里写图片描述

  1. 绘制当前视图的背景。

  2. 保存当前画布的堆栈状态,并且在在当前画布上创建额外的图层,以便接下来可以用来绘制当前视图在滑动时的边框渐变效果。

  3. 绘制当前视图的内容。

  4. 绘制当前视图的子视图的内容。

  5. 绘制当前视图在滑动时的边框渐变效果。

  6. 绘制当前视图的滚动条。

Step1:绘制视图View的背景
代码第2-5行,获取当前View是否需要绘制背景的标志dirtyOpaque ,代码第22-24行,根据这个标志来决定是否绘制视图View的背景。如果需要绘制背景,那么进入View类中的drawBackground方法:

/**
     * Draws the background onto the specified canvas.
     *
     * @param canvas Canvas on which to draw the background
     */
    private void drawBackground(Canvas canvas) {
        final Drawable background = mBackground;
        if (background == null) {
            return;
        }

        if (mBackgroundSizeChanged) {
            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
            mBackgroundSizeChanged = false;
            mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
        }

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

        final int scrollX = mScrollX;
        final int scrollY = mScrollY;
        if ((scrollX | scrollY) == 0) {
            background.draw(canvas);
        } else {
            canvas.translate(scrollX, scrollY);
            background.draw(canvas);
            canvas.translate(-scrollX, -scrollY);
        }
    }

该方法用来描述1,绘制当前View的背景的,在绘制背景前,调用background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);方法设置背景的大小,之后调用Drawable的对象backgroud的draw方法完成背景的绘制。

Step2:保存画布canvas的边框参数

代码第27-29获取当前视图View水平或者垂直方向是否需要绘制边框渐变效果,如果不需要绘制边框的渐变效果,就无需执行上面的2,5了。那么就直接执行上面的3,4,6步骤。这里描述的就是我们的ListView滑动到最底端时,底部会有一个淡蓝色的半圆形的边框渐变背景效果。

假如我们需要绘制视图View的边框渐变效果,那么我们继续分析步骤2,3,4,5,6。

代码第55-134行:这段代码用来检查是否需要保存参数canvas所描述的一块画布的堆栈状态,并且创建额外的图层来绘制当前视图在滑动时的边框渐变效果。视图的边框是绘制在内容区域的边界位置上的,而视图的内容区域是需要排除成员变量mPaddingLeft、mPaddingRight、mPaddingTop和mPaddingBottom所描述的视图内边距的。此外,视图的边框有四个,分别位于视图的左、右、上以及下内边界上。因此,这段代码首先需要计算出当前视图的左、右、上以及下内边距的大小,以便得到边框所要绘制的区域。

Step3:绘制视图View的内容

代码第138行我们可以看到,根据条件绘制当前视图View的内容,此处调用了View的成员方法onDraw来绘制视图View的内容,我们来看看onDraw成员方法的实现:

/**
     * Implement this to do your drawing.
     *
     * @param canvas the canvas on which the background will be drawn
     */
    protected void onDraw(Canvas canvas) {
    }

预料之中,该方法体里面是一个空实现,也就是视图View将绘制的逻辑留给继承它的子类去实现,这也就是为什么我们在自定义View的时候必须去实现其父类的onDraw方法来完成自己对内容的绘制。

Step4:绘制当前视图View的子视图

代码第141行调用View的成员方法dispatchDraw(canvas);来绘制它的子视图,我们进入dispatchDraw(canvas);方法窥探其实现逻辑:

/**
     * Called by draw to draw the child views. This may be overridden
     * by derived classes to gain control just before its children are drawn
     * (but after its own view has been drawn).
     * @param canvas the canvas on which to draw the view
     */
    protected void dispatchDraw(Canvas canvas) {

    }

同样你会发现,这也是一个空实现,既然是这样,那么其实现的逻辑也会在它的子类中实现了,由于只有ViewGroup容器才有其子视图,因此,该方法的实现应该在ViewGroup类中,我们进入ViewGroup类中看其源码如下:

 @Override
    protected void dispatchDraw(Canvas canvas) {
        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
        final int childrenCount = mChildrenCount;
        final View[] children = mChildren;
        int flags = mGroupFlags;
        //判断当前ViewGroup容器是否设置的布局动画
        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;

            final boolean buildCache = !isHardwareAccelerated();
            //遍历给每个子视图View设置动画效果
            for (int i = 0; i < childrenCount; i++) {
                final View child = children[i];
                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
                    final LayoutParams params = child.getLayoutParams();
                    attachLayoutAnimationParameters(child, params, i, childrenCount);
                    bindLayoutAnimation(child);
                    if (cache) {
                        child.setDrawingCacheEnabled(true);
                        if (buildCache) {
                            child.buildDrawingCache(true);
                        }
                    }
                }
            }
            //获得布局动画的控制器
            final LayoutAnimationController controller = mLayoutAnimationController;
            if (controller.willOverlap()) {
                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
            }
            //开始布局动画
            controller.start();

            mGroupFlags &= ~FLAG_RUN_ANIMATION;
            mGroupFlags &= ~FLAG_ANIMATION_DONE;

            if (cache) {
                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
            }
            //设置布局动画的监听事件
            if (mAnimationListener != null) {
                mAnimationListener.onAnimationStart(controller.getAnimation());
            }
        }

        int clipSaveCount = 0;
        //是否需要剪裁边距
        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
        if (clipToPadding) {
            clipSaveCount = canvas.save();
            //对画布进行边距剪裁
            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
                    mScrollX + mRight - mLeft - mPaddingRight,
                    mScrollY + mBottom - mTop - mPaddingBottom);
        }

        // We will draw our child's animation, let's reset the flag
        mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;
        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;

        boolean more = false;
        final long drawingTime = getDrawingTime();

        if (usingRenderNodeProperties) canvas.insertReorderBarrier();
        // Only use the preordered list if not HW accelerated, since the HW pipeline will do the
        // draw reordering internally
        final ArrayList<View> preorderedList = usingRenderNodeProperties
                ? null : buildOrderedChildList();
        final boolean customOrder = preorderedList == null
                && isChildrenDrawingOrderEnabled();
        //遍历绘制当前视图的子视图View
        for (int i = 0; i < childrenCount; i++) {
            int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
            final View child = (preorderedList == null)
                    ? children[childIndex] : preorderedList.get(childIndex);
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        if (preorderedList != null) preorderedList.clear();

        // Draw any disappearing views that have animations
        if (mDisappearingChildren != null) {
            final ArrayList<View> disappearingChildren = mDisappearingChildren;
            final int disappearingCount = disappearingChildren.size() - 1;
            // Go backwards -- we may delete as animations finish
            for (int i = disappearingCount; i >= 0; i--) {
                final View child = disappearingChildren.get(i);
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        if (usingRenderNodeProperties) canvas.insertInorderBarrier();

        if (debugDraw()) {
            onDebugDraw(canvas);
        }

        if (clipToPadding) {
            canvas.restoreToCount(clipSaveCount);
        }

        // mGroupFlags might have been updated by drawChild()
        flags = mGroupFlags;

        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
            invalidate(true);
        }

        //更新布局动画的监听事件
        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
                mLayoutAnimationController.isDone() && !more) {
            // We want to erase the drawing cache and notify the listener after the
            // next frame is drawn because one extra invalidate() is caused by
            // drawChild() after the animation is over
            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
            final Runnable end = new Runnable() {
               public void run() {
                   notifyAnimationListener();
               }
            };
            post(end);
        }
    }

分析:
1.代码第8-45行,判断当前ViewGroup布局是否设置了布局动画,如果设置了,则条件满足,给每个子视图View设置布局动画,那么什么情况下,该条件满足呢?当你在布局中使用ViewGroup容器布局,且设置了android:animateLayoutChanges=”true”属性,那么该条件满足,每个子视图View出现的时候都会有一个默认的动画效果。关于容器布局动画,具体详情可以参考我的另外一篇博客:Android属性动画Property Animation系列三之LayoutTransition(布局容器动画) ,这里面详细介绍了布局容器动画的各种使用技巧。

2.代码第49-56行,对当前视图的画布canvas进行边距裁剪,把不需要绘制内容的边距裁剪掉。

3.代码第73-80行,遍历绘制当前容器布局ViewGroup的子视图,其中调用了成员方法drawChild来完成子视图的绘制。

4.代码第83-92行,当子视图设置了消失动画时,遍历绘制布局容器中需要消失的子视图。关于子视图消失动画,具体详情可以参考我的另外一篇博客:Android属性动画Property Animation系列三之LayoutTransition(布局容器动画)

我们现在来分析下ViewGroup中的drawChild方法,看看它是怎么绘制子视图的:

/**
     * Draw one child of this View Group. This method is responsible for getting
     * the canvas in the right state. This includes clipping, translating so
     * that the child's scrolled origin is at 0, 0, and applying any animation
     * transformations.
     *
     * @param canvas The canvas on which to draw the child
     * @param child Who to draw
     * @param drawingTime The time at which draw is occurring
     * @return True if an invalidate() was issued
     */
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

是不是预料之中的事情,此处又调用View类中的draw方法来绘制视图,因此形成了一个嵌套调用,知道所有的子视图View绘制结束。到此关于视图View绘制已经基本完成。

Step5:绘制滑动时边框的渐变效果

代码第143-183:绘制当前容器视图ViewGroup的边框渐变效果。

Step6:绘制滚动条

代码第186行:绘制当前视图View的滑动条。此处调用了内部成员方法onDrawScrollBars来绘制滚动条,我们进入源码来窥探一下其如何实现:

 protected final void onDrawScrollBars(Canvas canvas) {
        // scrollbars are drawn only when the animation is running
        final ScrollabilityCache cache = mScrollCache;
        //滚动条是否有缓存
        if (cache != null) {

            int state = cache.state;
            //滚动条不显示时,直接返回,也就是不绘制滚动条
            if (state == ScrollabilityCache.OFF) {
                return;
            }

            boolean invalidate = false;
            //滚动条是否可见
            if (state == ScrollabilityCache.FADING) {
                // We're fading -- get our fade interpolation
                if (cache.interpolatorValues == null) {
                    cache.interpolatorValues = new float[1];
                }

                float[] values = cache.interpolatorValues;

                // Stops the animation if we're done
                if (cache.scrollBarInterpolator.timeToValues(values) ==
                        Interpolator.Result.FREEZE_END) {
                    cache.state = ScrollabilityCache.OFF;
                } else {
                    cache.scrollBar.setAlpha(Math.round(values[0]));
                }

                // This will make the scroll bars inval themselves after
                // drawing. We only want this when we're fading so that
                // we prevent excessive redraws
                invalidate = true;
            } else {
                // We're just on -- but we may have been fading before so
                // reset alpha
                //设置滚动条完全可见
                cache.scrollBar.setAlpha(255);
            }


            final int viewFlags = mViewFlags;

            final boolean drawHorizontalScrollBar =
                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
            final boolean drawVerticalScrollBar =
                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
                && !isVerticalScrollBarHidden();

            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
                final int width = mRight - mLeft;
                final int height = mBottom - mTop;

                final ScrollBarDrawable scrollBar = cache.scrollBar;

                final int scrollX = mScrollX;
                final int scrollY = mScrollY;
                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;

                int left;
                int top;
                int right;
                int bottom;
                //绘制水平滚动条
                if (drawHorizontalScrollBar) {
                    int size = scrollBar.getSize(false);
                    if (size <= 0) {
                        size = cache.scrollBarSize;
                    }

                    scrollBar.setParameters(computeHorizontalScrollRange(),
                                            computeHorizontalScrollOffset(),
                                            computeHorizontalScrollExtent(), false);
                    final int verticalScrollBarGap = drawVerticalScrollBar ?
                            getVerticalScrollbarWidth() : 0;
                    top = scrollY + height - size - (mUserPaddingBottom & inside);
                    left = scrollX + (mPaddingLeft & inside);
                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
                    bottom = top + size;
                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
                    if (invalidate) {
                        invalidate(left, top, right, bottom);
                    }
                }
                //绘制垂直滚动条
                if (drawVerticalScrollBar) {
                    int size = scrollBar.getSize(true);
                    if (size <= 0) {
                        size = cache.scrollBarSize;
                    }

                    scrollBar.setParameters(computeVerticalScrollRange(),
                                            computeVerticalScrollOffset(),
                                            computeVerticalScrollExtent(), true);
                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
                        verticalScrollbarPosition = isLayoutRtl() ?
                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
                    }
                    switch (verticalScrollbarPosition) {
                        default:
                        case SCROLLBAR_POSITION_RIGHT:
                            left = scrollX + width - size - (mUserPaddingRight & inside);
                            break;
                        case SCROLLBAR_POSITION_LEFT:
                            left = scrollX + (mUserPaddingLeft & inside);
                            break;
                    }
                    top = scrollY + (mPaddingTop & inside);
                    right = left + size;
                    bottom = scrollY + height - (mUserPaddingBottom & inside);
                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
                    if (invalidate) {
                        invalidate(left, top, right, bottom);
                    }
                }
            }
        }
    }

分析:
1.代码第9行,判断是否需要绘制当前视图View的滚动条。如果你给当前视图View设置了android:scrollbars=”none”属性,时就不会绘制滚动条,也就是不显示滚动条。

2.代码第15行,判断当前视图View的滚动条是否可消失。如果你给当前视图View设置了android:fadeScrollbars=”true”属性时,你不滑动,滚动条隐藏,你滑动时,滚动条显示,有代码可以看出,此处是通过改变滚动条的透明度来实现滚动条隐藏和显示的。

3.代码第35-39行,当前视图View的滚动条设置成完全可见,也就是你设置了该属性android:fadeScrollbars=”false”。不管你是否滑动View,滚动条一直可见。

4.代码第43-116行,都是绘制水平或者垂直滚动条的逻辑。

至此,视图View的整个绘制流程就结束了。最后上一张绘制流程图如下:

这里写图片描述

绘制Draw总结:

1.View绘制的画布参数canvas是由surface对象获得,言外之意,View视图绘制最终会绘制到Surface对象去。关于Surface内容参考3-1节。

2.由3-2小节我们了解到,父类View绘制主要是绘制背景,边框渐变效果,进度条,View具体的内容绘制调用了onDraw方法,通过该方法把View内容的绘制逻辑留给子类去实现。因此,我们在自定义View的时候都一般都需要重写父类的onDraw方法来实现View内容绘制。

3.不管任何情况,每一个View视图都会绘制 scrollBars滚动条,且绘制滚动条的逻辑是在父类View中实现,子类无需自己实现滚动条的绘制。其实TextView也是有滚动条的,可以通过代码让其显示滚动条和内容滚动效果。你只需在TextView布局设置android:scrollbars=”vertical”属性,且在代码中进行如下设置

textView.setMovementMethod(ScrollingMovementMethod.getInstance()); 

这样既可让你的TextView内容可以滑动,且有滚动条。

4.ViewGroup绘制的过程会对每个子视图View设置布局容器动画效果,如果你在ViewGroup容器布局里面设置了如下属性的话:

android:animateLayoutChanges="true"

总结:

通过以上分析:视图View的绘制流程基本了解清楚,主要分三个步骤:measure测量,layout布局,draw绘制。当然这三个步骤并不是都要执行,在执行每一步之前都会判断当前视图是否需要重新measure测量,是否需要重新layout布局,是否需要重新draw绘制。其中很多细节性的东西,望有意了解者可以自己跟着源码思路自己分析一遍,以便自己完全理解。

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

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页