Android应用篇 - 从源码角度来理解 View 的绘制流程

上一篇文章从几个场景分析了下 View 的绘制流程,这篇文章我们来 read the fuck code!

本文源代码基于 Android 7.0。 

 

目录:

  1. handleResumeActivity()
  2. performTraversals()
  3. performMeasure()
  4. performLayout()
  5. performDraw()

 

 

1. handleResumeActivity()

/base/core/java/android/app/ActivityThread.java

onResume() 之后才是 Activity 真正可见和可交互的状态,那就从 ActivityThread.handleResumeActivity() 作为入口。

    final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
            // ...
            if (r.activity.mVisibleFromClient) {
                    // 添加视图
                    r.activity.makeVisible();
            }
            // ...
    }

狂删一通代码, 因为这不是讲 AMS 或者 WMS,我们这边只看调用链。makeVisible() 这便来到了 Activity 世界:

/base/core/java/android/app/Activity.java

    void makeVisible() {
        // 如果Window没有被添加,则addView添加decorView
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();
            // 进入WindowManagerGlobal.addView,这边是添加DecorView,根view
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        // 设置decorView可见
        mDecor.setVisibility(View.VISIBLE);
    }

wm.addView() 最终会调用到 WindowManagerGlobal.addView(),这个前面的 Framework 相关的文章有写过。

/base/core/java/android/view/WindowManagerGlobal.java

    // 添加View
    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            // 每次调用global.addView()都会创建一个ViewRootImpl,它是decorView与WMS沟通的桥梁
            root = new ViewRootImpl(view.getContext(), display);

            // 设置LayoutParams
            view.setLayoutParams(wparams);

            // 加到mViews, mRoots, mParams集合中
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }

        // do this last because it fires off messages to start doing things
        try {
            // ViewRootImpl设置View
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            // ...
        }
    }

ViewRootImpl 实例化出来了,实例化出来然后被加到 mRoots (一个存放 ViewRootImpl 实例的 Arraylist) 中,同时 decorView 被添加进 mViews 中,最后我们看到调用了 root.setView() 方法。

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

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {

    //...
    requestLayout();
    //...
}

好熟悉的方法名,看看它里面做了什么:

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

    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            // ...
        }
    }

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

    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            // ...
            performTraversals();
            // ...
        }
    }

  • checkThread():只能在主线程更新 UI。
  • performTraversals()。

接下来的篇幅将从 performTraversals() 这个方法作为入口来写。

 

 

2. performTraversals()

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

private void performTraversals() {
    // ...
    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
    // 测量
    performMeasure(childWidthMeasureSpec,childHeightMeasureSpec);
    // 布局
    performLayout(lp, mWidth, mHeight);
    // 绘制
    performDraw();
    // ...
}

接着分三个小节来展开说这三个方法。

 

 

3. performMeasure()

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

    private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
        }
    }

盗用一张图 - View 树的 measure 流程,画图太费时费力了: 


这里调用了 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec) 这个方法,那么这里的 mView 是什么东西呢,当然是从根视图开始 measure 了,所以就是 decorView 了。decorView 是个 FrameLayout所以我们就来看 FrameLayout 的measure() 方法。FrameLayout 里面没有 measure(),只有 onMeasure(),measure() 方法在其父类 View 里,measure() 方法中会调用 onMeasure():

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

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

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

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                // ...
            }
        }

        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

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

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

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

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

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

遍历了父视图下面的子视图,然后调用 measureChildWithMargins() 方法来进行测量子视图,这个方法位于 ViewGroup 类中:

    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

根据父视图的大小还有 mode,以及自己的  Padding和 Margin 还有 LayoutParams 来测量,先看下这里面的方法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) {
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

根据 mode 和 size 测量出自己的大小之后,会把 mode 和 size 调用 makeMeasureSpec 继续合成。

继续看 measureChildWithMargins() 方法最后会在调用 View 的 measure(),如果这个 View 还是个 ViewGoup 的话,那就会递归调用 measure() 方法,如果是 View 的话,那就会调用 View 的 measure(),也就是会调用到 onMeasure()。

 

 

4. performLayout()

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

测量完成后,就开始来布局了。

    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        // ...
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        // ...
    }

和 measure() 一样,也是递归调用。看看 FrameLayout 的 layout(),在 FrameLayout 的父类 View 中:

      public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
        }
        // ...
    }
    
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

里面会调用 onLayout(),onLayout() 是一个空实现,子类可以在里面做一些自己的事,来看看 FrameLayout 的 onLayout():

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

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

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

                int childLeft;
                int childTop;

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

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

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

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

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

递归调用过程,和 measure() 流程一样。

 

 

5. performDraw()

盗图,画图好累,码字好累 - draw 流程图:

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

    private void performDraw() {
        // ...
        try {
            draw(fullRedrawNeeded);
        } finally {
            mIsDrawing = false;
        }
        // ...
    }

    private void draw(boolean fullRedrawNeeded) {
        // ...
        if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty))             {
               return;
            }
        // ...
    }

   private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {
       // ...
       mView.draw(canvas);
       // ...
   }

和上面的 measure、layout 一样,来看看 View 的 draw():

    public void draw(Canvas canvas) {
        // 画背景
        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // 回调 onDraw() 
            if (!dirtyOpaque) onDraw(canvas);

            // 分发 draw()
            dispatchDraw(canvas);

            // 绘制 foreground
            onDrawForeground(canvas);
            return;
        }
        // ... 后面情况也是这几个步骤
    }

先画背景,然后 onDraw() 画自己,接着 dispatchDraw() 分发绘制子 View,最后画前景。来看看 FrameLayout 对dispatchDraw() 的实现,在它的父类 ViewGroup 中:

    @Override
    protected void dispatchDraw(Canvas canvas) {
        // ...
        final int childrenCount = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < childrenCount; i++) {
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        // Draw any disappearing views that have animations
        if (mDisappearingChildren != null) {
            for (int i = disappearingCount; i >= 0; i--) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        // ...
    }

    rotected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

最后又是一个递归调用过程。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值