View的工作原理

View的繪制是從ViewRootImpl的setView開始的,

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
            int userId) {
    。。。
    requestLayout();
    。。。

setView方法調(diào)用了requestLayout

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

requestLayout()中執(zhí)行了scheduleTraversals(Traversals的意思是遍歷)

 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

scheduleTraversals中又執(zhí)行了mTraversalRunnable;

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

mTraversalRunnable執(zhí)行了doTraversal()方法

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

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

最后走到了PerformTraversals()
performTraversals方法中又三個(gè)比較重要的方法
performMeasure---測量
performLayout---布局
performDraw---繪制

performMeasure流程

image.png

首先跟據(jù)屏幕的寬高和DecorView的LayoutParams計(jì)算出DecorView的MeasureSpec;
那么DecorView的LayoutParams在哪呢?---待分析

private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {
        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            // 精確模式,大小是窗口大小
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
           // 最大模式,大小不得超過窗口大小
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            // 精確大小,大小即為rootDimension
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

分析都在上面代碼的注釋中;
由此,DecorView的MeasureSpec已經(jīng)生成,下面就會(huì)調(diào)用DecorView的Measure方法

image.png

為啥說此處的mView就是DecorView,是在調(diào)用setView方法的時(shí)候傳入的,此處不在贅述;
需要去看WindowManager.addView的流程;

image.png

由于DecorView本身是一個(gè)FramLayout,所以他的Measure過程肯定會(huì)遵循View,ViewGroup和FramLayout的measure過程;

由于ViewGroup和FrameLayout都沒有實(shí)現(xiàn)measure,所以只會(huì)執(zhí)行View的measure方法;

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
      onMeasure(widthMeasureSpec, heightMeasureSpec);
}

View的默認(rèn)onMeasure方法實(shí)現(xiàn):

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

但是FrameLayout會(huì)復(fù)習(xí)這個(gè)方法:

@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) {
                // 注釋1調(diào)用ViewGroup的方法 
                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());
        }

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

因此方法會(huì)直接調(diào)用FrameLayout里面的onMeasure方法,并不會(huì)走到View里面的onMeasure方法;
FrameLayout首先執(zhí)行了一個(gè)for循環(huán),讓他的每個(gè)子view都去執(zhí)行measureChildWithMargin;
注釋1處調(diào)用了ViewGroup的measureChildWithMargin方法;

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

        // 注釋1,又開始調(diào)用view的measure方法
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

從注釋1可以看出,這個(gè)方法是viewGroup遞歸的開始,也就是
view.measure會(huì)調(diào)用view的onMeasure方法
---》如果view是一個(gè)ViewGroup的具體實(shí)現(xiàn)類,則會(huì)調(diào)用實(shí)現(xiàn)類的onMeasure,比如framlayout方法
---》實(shí)現(xiàn)類一般會(huì)使用for循環(huán),去遍歷子view
---》子view如果依舊是一個(gè)ViewGroup的實(shí)現(xiàn)類,則會(huì)繼續(xù)調(diào)用子VIew的onMeasure,繼續(xù)遍歷子View的measure
---》直到子VIew不是一個(gè)ViewGroup類型,則調(diào)用子VIew的onMeasure方法完成測量

上面的measureChildWithMargins總共分成了2步;
1.通過父容器的MeasureSpec和子元素本身的LayoutParam決定子View的MeasureSpec
2.調(diào)用子view的measure方法;
通過這個(gè)遞歸,就會(huì)得到所有FramLayout所有子View的測量寬高,也就是mMeasuredWidth和mMeasuredHeight
最后就是比大小,由于FrameLayout的寬高是由所有子VIew中的最大寬和所有子view中的最大高決定的(當(dāng)然還要考慮一下margin);
就得的了frameLayout自己的寬高,也就是DecorView的寬高;

在討論ViewGroup的測量過程,是不能直接看ViewGroup的,因?yàn)閂iewGroup畢竟是個(gè)抽象的,他不會(huì)直接實(shí)現(xiàn)onMeasure方法,他是把這個(gè)過程交給子類去實(shí)現(xiàn)的,由子類的for循環(huán)+viewgroup的measureChildWithMargins完成整個(gè)View樹的測量,
為啥ViewGroup不自己實(shí)現(xiàn)呢,因?yàn)樗膊恢雷约旱牟季质巧稑友剑?/p>

整個(gè)測量過程一定是父容器的MeasureSpec+自身的layoutParam一起,決定了自身的MeasureSpec,等自身的MeasureSpec確定了,就可以通過onMeasure方法去完成最終的測量,所有頂端的View就是DecorView,那么DecorView的父容器就只能從他的Window中去獲??;

完成測量后,整個(gè)view樹上的所有的view都會(huì)有兩個(gè)測量值,mMeasuredWidth和mMeasuredHeight,通過setMeasuredDimensionRaw方法設(shè)置;這也是measure階段的產(chǎn)出,供給layout使用的;

performLayout布局

private void performTraversals() {
     performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);//1
     ...
    performLayout(lp, mWidth, mHeight); //2
    ...
    performDraw();//3
}

傳入的三個(gè)參數(shù):
lp:window的layoutParam
mWidth:
mHeight:


image.png

此處的host就是DecorView

image.png

此處先通過setFrame設(shè)置了自身的屬性;mLeft,mTop,mRight,mBottom

然后在調(diào)用view的onLayout方法,


image.png

可以看到這邊是一個(gè)空實(shí)現(xiàn),為啥會(huì)是空的呢,因?yàn)関iew自己的屬性值剛剛已經(jīng)通過setFrame方法自己設(shè)置了??;

由于DecorView是一個(gè)FrameLayout,所有雖然不會(huì)View的onLayout為空,但是會(huì)執(zhí)行
FrameLayout的onLayout方法;

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

此處又是通過一個(gè)for循環(huán),完成遞歸,可以看出來的是,每一個(gè)子view都是通過先確定子view的left和top,再根據(jù)測量寬高mMeasuredWidth和mMeasuredHeight,計(jì)算出他的right和bottom;
還是很容易理解的;

mMeasuredWidth:View的測量寬
mMeasuredHeight:View的測量高
getWidth():實(shí)際寬
getHeight():實(shí)際高


image.png

所有實(shí)際寬高是在layout產(chǎn)生的;

layout階段作用根據(jù)測量階段的寬高算出他的四個(gè)值,
mLeft,mTop,mRight,mBottom
而這四個(gè)值,又會(huì)對draw階段產(chǎn)生實(shí)際影響

performDraw流程

明天繼續(xù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容