View 绘制流程

从前面的WindowManager文章中,Activity的窗口创建流程可以看到,在ActivityThread.handleResumeActivity方法中回调onResume,然后调用wm.addView(decor, l)添加DecorView,同时创建ViewRootImpl对象,ViewRootImpl用于管理view的绘制和事件的分发,由此可以看出一个Activity对应一个ViewRootImpl 和一个DecorView根视图。而View的绘制流程从ViewRoot的performTraversals方法开始,经过measure、layout、draw三个过程分别完成计算大小、位置以及绘制。


SequenceDiagram1.png

一、measure过程

ViewRootImpl中的performTraversals() 方法调用performMeasure() 用来测量view的大小。
下面我们从计算根视图DecorView的大小开始。

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

这里mView 是前面setView传过来的DecorView,调用到父类的View的measure函数。

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

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

        // Optimize layout by avoiding an extra EXACTLY pass when the view is
        // already measured as the correct size. In API 23 and below, this
        // extra pass is required to make LinearLayout re-distribute weight.
        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
                || heightMeasureSpec != mOldHeightMeasureSpec;
        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
        final boolean needsLayout = specChanged
                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
        //forceLayout目前view正在执行布局操作,needsLayout当前视图大小跟之前不一样时需要重新计算
        if (forceLayout || needsLayout) {
            // 清空flag,PFLAG_MEASURED_DIMENSION_SET 是控件onMeasure中调用setMeasuredDimension()时设置的flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // 真正的测量控件大小,调用当前view的onMeasure 方法
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            // onMeasure 中没有调用 setMeasuredDimension(),将会抛出如下异常
            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
                throw new IllegalStateException("View with id " + getId() + ": "
                        + getClass().getName() + "#onMeasure() did not set the"
                        + " measured dimension by calling"
                        + " setMeasuredDimension()");
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }
        //保存当前值
        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

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

View.java 中的measure() 方法是final类型,子类不能复写。measure方法用于提供父View对长宽的约束信息,控制什么时候view需要被重新计算,真正的计算View尺寸是在onMeasure中进行的。
或者说View的measure是View的测量框架,用户不可以修改其逻辑,具体的大小计算在各个空间的onMeasure方法中实现。
再看DecorView的onMeasure

/frameworks/base/core/java/com/android/internal/policy/DecorView.java

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

        ... ...
    }

DecorView.onMeasure主要对AT_MOST情况时的长宽作了调整,因为此时是Activity,不会走到AT_MOST条件,直接调用父类FrameLayout.onMeasure

/frameworks/base/core/java/android/widget/FrameLayout.java

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //得到view个数
        int count = getChildCount();

        //计算所有子View中的最大宽高
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                //这里会调用子View中的measure方法,实现递归的计算所有视图的大小
                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);
                    }
                }
            }
        }
        ... ...

        //把宽高信息设置到View中 
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));

        ... ...
    }

FrameLayout的主要工作:

1.调用子View的measureChildWithMargins方法,这个函数里会调用View.measure方法,递归计算子View的宽高信息。

2.计算出合适的宽高,然后调用setMeasuredDimension设置测量结果

m.png

思考: 定义为wrap_content 的view的大小计算过程?

getChildMeasureSpec用于产生子view测量规范,当子view为wrap_content 时,父view是Exactly 或者 At_Most 都会给子view的spec 为:mode At_Most,size 父view大小,因为此时子view大小不确定。

(1)如果是view(TextView),父view的spec mode为 At_Most,size 为父view大小, 取父view的size 和子view的size的最小值作为最终长宽,子view size 可以根据父view的 padding ,子view的margin以及内容大小(textsize 背景图片等)确定。

(2)如果是viewgroup(LinearLayout 等),调用其子view.measure,然后调用到子view.onMeasure ,如果子view大小确定,传给子view的spec 为 Exactly + 子view大小(参考getChildMeasureSpec源码),子view 的onMeasure方法计算出确定值后,回到当前view可以得到子view大小,根据子view大小,以及父view给的at_most ,两者取较小,即为当前view大小。如果其子view还是viewgroup,则继续递归调用view.measure,控件.onMeasure去计算各个子view真实大小。

二、layout过程

ViewRootImpl.performLayout是计算各个view位置的开始。

/frameworks/base/core/java/android/view/ViewRootImpl.java

    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        ... ...

        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
        try {
            //layout四个参数l,t,r,b分别代表该view相对于父view的位置
            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        ... ...
            }
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

这里host是DecorView, DecorView没有实现layout方法, 直接调用到View.layout。

/frameworks/base/core/java/android/view/View.java

    public void layout(int l, int t, int r, int b) {
        
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //调用该View的onLayout做进一步处理
            onLayout(changed, l, t, r, b);
        }
    }

/frameworks/base/core/java/com/android/internal/policy/DecorView.java

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        ... ...
    }

直接调用父类FrameLayout.onLayout

/frameworks/base/core/java/android/widget/FrameLayout.java

    @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();
        //根据子View的外边距及Gravity信息,计算子View的位置
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                //onMeasure时得到的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;

                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遍历布局各个子View
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

根据当前view的位置内边距和子view的宽高及外边距确定子View的位置,然后再调用View.layout ,递归实现所有子View位置的计算。

三、draw过程

同样从ViewRootImpl的performDraw方法开始View的绘制draw 过程

/frameworks/base/core/java/android/view/ViewRootImpl.java

    private void performDraw() {
        ... ...

        mIsDrawing = true;
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
        try {
            draw(fullRedrawNeeded);
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

主要调用ViewRootImpl的draw方法

    private void draw(boolean fullRedrawNeeded) {
        //mSurface表示绘图界面,所有view都绘制在上面
        Surface surface = mSurface;
        if (!surface.isValid()) {
            return;
        }

        if (DEBUG_FPS) {
            trackFPS();
        }
        //Jit相关
        if (!sFirstDrawComplete) {
            synchronized (sFirstDrawHandlers) {
                sFirstDrawComplete = true;
                final int count = sFirstDrawHandlers.size();
                for (int i = 0; i< count; i++) {
                    mHandler.post(sFirstDrawHandlers.get(i));
                }
            }
        }

        scrollToRectOrFocus(null, false);

        if (mAttachInfo.mViewScrollChanged) {
            mAttachInfo.mViewScrollChanged = false;
            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
        }

        //判断当前界面是否处于滚动状态
        boolean animating = mScroller != null && mScroller.computeScrollOffset();
        final int curScrollY;
        if (animating) {
            curScrollY = mScroller.getCurrY();
        } else {
            curScrollY = mScrollY;
        }
        //如果当前Y轴位置跟之前不相等则调用onRootViewScrollYChanged 通知view发生滚动
        if (mCurScrollY != curScrollY) {
            mCurScrollY = curScrollY;
            fullRedrawNeeded = true;
            if (mView instanceof RootViewSurfaceTaker) {
                 //只有DecorView实现了接口RootViewSurfaceTaker
                ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
            }
        }
        //窗口是否处于缩放状态
        final float appScale = mAttachInfo.mApplicationScale;
        final boolean scalingRequired = mAttachInfo.mScalingRequired;

        int resizeAlpha = 0;
        //矩形绘制区域
        final Rect dirty = mDirty;
        //如果应用使用SurfaceView自己在渲染线程绘制,那么清空dirty,无需继续绘制
        if (mSurfaceHolder != null) {
            // The app owns the surface, we won't draw.
            dirty.setEmpty();
            if (animating && mScroller != null) {
                mScroller.abortAnimation();
            }
            return;
        }
        //设置绘制区域的大小
        if (fullRedrawNeeded) {
            mAttachInfo.mIgnoreDirtyState = true;
            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
        }

        ... ...

        //重新绘制UI
        //需要硬件加速
        if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
            if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
                

                mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
            } else {
    
                //调用drawSoftware
                if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                    return;
                }
            }
        }

        if (animating) {
            mFullRedrawNeeded = true;
            //请求下一次绘制
            scheduleTraversals();
        }
    }

/frameworks/base/core/java/android/view/ViewRootImpl.java

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

        // Draw with software renderer.
        final Canvas canvas;
        try {
            ... ...
            //获得Canvas对象并锁定画布
            canvas = mSurface.lockCanvas(dirty);
            ... ...

        }

        try {
            ... ...
            try {
                ... ...
                //调用DecorView 的draw方法在画布上绘制UI
                mView.draw(canvas);
                ... ...
            } 
        } finally {
            try {
                //调用Surface的unlockCanvasAndPost方法请求SurfaceFlinger服务渲染画布里面图形缓冲区,让UI显示出来
                surface.unlockCanvasAndPost(canvas);
            } catch (IllegalArgumentException e) {
                Log.e(mTag, "Could not unlock surface", e);
                mLayoutRequested = true;    // ask wm for a new surface next time.
                //noinspection ReturnInsideFinallyBlock
                return false;
            }

        }
        return true;
    }

继续看下DecorView.draw

/frameworks/base/core/java/com/android/internal/policy/DecorView.java

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        if (mMenuBackground != null) {
            mMenuBackground.draw(canvas);
        }
    }

主要调用父类View.draw 方法,View的draw主要完成以下工作:

  1. 绘制背景

  2. 如果需要,保存画布层级用来绘制当前视图在滑动时的边框渐变效果

  3. 绘制当前视图内容

  4. 绘制他的孩子

  5. 如果需要,绘制当前视图在滑动时的渐变效果并存储图层。

  6. 绘制滚动条等

/frameworks/base/core/java/android/view/View.java

    @CallSuper
    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);
        }

        // 当前视图不是出于滑动状态则跳过第2、5步 
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

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

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

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

            // we're done...
            return;
        }
        ... ...
        // Step 2, save the canvas' layers
        //如果当前视图背景颜色为0,创建额外的图层绘制滑动效果,否则使用这个背景颜色作为渐变效果
        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
        //调用当前视图的onDraw方法
        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);

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

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

Step 3 绘制当前视图这里调用DecorView 的onDraw 方法,DecorView.onDraw直接调用父类onDraw,最后调用到View.onDraw,没有特别要绘制的内容。下面重点看下Step 4绘制各个子View过程,只有容器视图才需要绘制子视图,所以View中的dispatchDraw 方法是空的,直接看下ViewGroup中的dispatchDraw方法:

/frameworks/base/core/java/android/view/ViewGroup.java

        @Override
    protected void dispatchDraw(Canvas canvas) {
        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
        final int childrenCount = mChildrenCount;
        final View[] children = mChildren;
        int flags = mGroupFlags;
        //需要绘制动画
        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
            final boolean buildCache = !isHardwareAccelerated();
            //遍历子View并给子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);
                }
            }
            //LayoutAnimation用于给ViewGroup里面子View设置动画效果
            final LayoutAnimationController controller = mLayoutAnimationController;
            if (controller.willOverlap()) {
                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
            }
            //启动动画
            controller.start();

            mGroupFlags &= ~FLAG_RUN_ANIMATION;
            mGroupFlags &= ~FLAG_ANIMATION_DONE;
            //通知注册了AnimationListener监听器的View开始动画
            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();
        final int transientCount = mTransientIndices == null ? 0 : mTransientIndices.size();
        int transientIndex = transientCount != 0 ? 0 : -1;
        // Only use the preordered list if not HW accelerated, since the HW pipeline will do the
        // draw reordering internally
        final ArrayList preorderedList = usingRenderNodeProperties
                ? null : buildOrderedChildList();
        final boolean customOrder = preorderedList == null
                && isChildrenDrawingOrderEnabled();
        //遍历子View,如果子View可见或者正在执行动画,那么调用drawChild绘制子View
        for (int i = 0; i < childrenCount; i++) {
            while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
                final View transientChild = mTransientViews.get(transientIndex);
                if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
                        transientChild.getAnimation() != null) {
                    more |= drawChild(canvas, transientChild, drawingTime);
                }
                transientIndex++;
                if (transientIndex >= transientCount) {
                    transientIndex = -1;
                }
            }

            final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
            final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        while (transientIndex >= 0) {
            // there may be additional transient views after the normal views
            final View transientChild = mTransientViews.get(transientIndex);
            if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
                    transientChild.getAnimation() != null) {
                more |= drawChild(canvas, transientChild, drawingTime);
            }
            transientIndex++;
            if (transientIndex >= transientCount) {
                break;
            }
        }
        if (preorderedList != null) preorderedList.clear();

        // Draw any disappearing views that have animations
        if (mDisappearingChildren != null) {
            final ArrayList 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;
        //重新绘制UI请求,会重新调用View绘制三部曲performMeasure,performLayout,performDraw
        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() {
               @Override
               public void run() {
                   notifyAnimationListener();
               }
            };
            post(end);
        }
    }

  1. dispatchDraw 中调用drawChild去绘制子View
    /frameworks/base/core/java/android/view/ViewGroup.java
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

调用View.draw用同样的方法绘制子View,实现了递归的绘制过程。

draw.png
  1. dispatchDraw动画绘制结束后通知监听器动画结束,注意这里使用了View.post, 结合注释目的是等待下一帧绘制完成后再檫除绘制缓存和通知动画监听器。那么看下为什么调用View.post 可以达到这个目的。

/frameworks/base/core/java/android/view/View.java

    public boolean post(Runnable action) {
       final AttachInfo attachInfo = mAttachInfo;
       if (attachInfo != null) {
           return attachInfo.mHandler.post(action);
       }

       // Postpone the runnable until we know on which thread it needs to run.
       // Assume that the runnable will be successfully placed after attach.
       getRunQueue().post(action);
       return true;
   }

post中分两种情况,第一种是 mAttachInfo不为null,直接post到mAttachInfo.mHandler所在线程,第二种放到一个消息队列中等待执行。
那么我们首先看下什么情况下mAttachInfo才不为null,mAttachInfo在dispatchAttachedToWindow方法中赋值。

/frameworks/base/core/java/android/view/View.java

    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
        mAttachInfo = info;
        ... ...
        // Transfer all pending runnables.
        if (mRunQueue != null) {
            mRunQueue.executeActions(info.mHandler);
            mRunQueue = null;
        }
        ... ...

    }

dispatchAttachedToWindow 在ViewRootImpl.java 的 performTraversals方法中被调用,在

/frameworks/base/core/java/android/view/ViewRootImpl.java

    private void performTraversals() {
        ... ...
        if (mFirst) {
            ... ...

            host.dispatchAttachedToWindow(mAttachInfo, 0);
            ... ...
        } 
        ... ...
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        ... ...
        performLayout(lp, mWidth, mHeight);
        ... ...
        performDraw();
        ... ...
    }

performTraversals前面第一个时序图中可以看到,在绘制界面时会被调用,
所以如果是第一次绘制则调用dispatchAttachedToWindow,因为一个Activity所有View执行完measure和layout后,mFirst才设为false。然后再看下mAttachInfo.mHandler属于哪个线程,mAttachInfo在ViewRootImpl 构造函数中初始化,mHandler是ViewRootImpl的handler,显然是运行在主线程。

/frameworks/base/core/java/android/view/ViewRootImpl.java

mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);

final ViewRootHandler mHandler = new ViewRootHandler();

前面第一个流程图中可以看出,ActivityThread.handleResumeActivity 时会创建ViewRootImpl 对象,并调用setView触发绘制流程,所以此时AttachInfo才不为null, 如果在Activity的onCreate过程中,就调用View.post那么AttachInfo为空,回到前面View.post方法中的mAttachInfo为null的情况:

/frameworks/base/core/java/android/view/View.java

    public boolean post(Runnable action) {
       final AttachInfo attachInfo = mAttachInfo;
       if (attachInfo != null) {
           return attachInfo.mHandler.post(action);
       }

       // Postpone the runnable until we know on which thread it needs to run.
       // Assume that the runnable will be successfully placed after attach.
       getRunQueue().post(action);
       return true;
   }

getRunQueue 得到HandlerActionQueue对象

/frameworks/base/core/java/android/view/View.java

   private HandlerActionQueue getRunQueue() {
       if (mRunQueue == null) {
           mRunQueue = new HandlerActionQueue();
       }
       return mRunQueue;
   }

/frameworks/base/core/java/android/view/HandlerActionQueue.java

public class HandlerActionQueue {
    private HandlerAction[] mActions;
    private int mCount;

    public void post(Runnable action) {
        postDelayed(action, 0);
    }

    public void postDelayed(Runnable action, long delayMillis) {
        final HandlerAction handlerAction = new HandlerAction(action, delayMillis);

        synchronized (this) {
            if (mActions == null) {
                mActions = new HandlerAction[4];
            }
            mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
            mCount++;
        }
    }
    ... ...
    public void executeActions(Handler handler) {
        synchronized (this) {
            final HandlerAction[] actions = mActions;
            for (int i = 0, count = mCount; i < count; i++) {
                final HandlerAction handlerAction = actions[i];
                handler.postDelayed(handlerAction.action, handlerAction.delay);
            }

            mActions = null;
            mCount = 0;
        }
    }
}

下面再看下HandlerActionQueue.post方法,直接调用postDelayed方法,然后将我们的Runnable对象封装成HandlerAction对象,放到数组mActions中,所以View.post方法中的getRunQueue().post(action)只是把Runnable放到了消息队列中,真正执行需要调用HandlerActionQueue.executeActions方法,这个方法在dispatchAttachedToWindow中调用,而dispatchAttachedToWindow又在ViewRootImpl.performTraversals中被调用,performTraversals从一个流程图中可以看到是Choreographer类 post 的TraversalRunnable到主线程的Handler执行的,所以我们调用View.post放在消息消息队列中的Runnable会在performTraversals中所有操作执行完再取出被执行。

这就是为什么在onCreate 里面我们使用View.post 可以得到控件的高宽,因为View.post里面的Runnable会在performMeasure,performLayout之后执行,即使View.dispatchAttachedToWindow在performMeasure,performLayout之前就被调用了。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView)findViewById(R.id.text);
        Log.d(TAG,"width="+text.getMeasuredWidth() + " ,height=" + text.getMeasuredHeight());
        text.post(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG,"post width="+text.getMeasuredWidth() + " ,height=" + text.getMeasuredHeight());
            }
        });

打印log:

06-01 14:35:38.800 3986-3986/com.example.srct.hdpi D/MainActivity: width=0 ,height=0
06-01 14:35:38.940 3986-3986/com.example.srct.hdpi D/MainActivity: post width=300 ,height=52

回到前面的dispatchDraw使用View.post 去通知监听器动画结束,可以保证在下一帧绘制完成再去通知动画结束的原因就分析完了~~

四、应用实例

最近写了分词功能的自定义控件,其中实现控件的onMeasure和onLayout方法,完成了以下的布局效果:

Screenshot_20180601-160927.png

Screenshot_20180601-160934.png

代码连接: https://github.com/MissMidou/Midou_BigBang

参考文章

  • 《深入浅出Android源代码》

你可能感兴趣的:(View 绘制流程)