View的工作原理

2023-02-23  本文已影响0人  重新起步

View的绘制是从ViewRootImpl的setView开始的,

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

setView方法调用了requestLayout

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

requestLayout()中执行了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中又执行了mTraversalRunnable;

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

mTraversalRunnable执行了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方法中又三个比较重要的方法
performMeasure---测量
performLayout---布局
performDraw---绘制

performMeasure流程

image.png
首先跟据屏幕的宽高和DecorView的LayoutParams计算出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已经生成,下面就会调用DecorView的Measure方法

image.png
为啥说此处的mView就是DecorView,是在调用setView方法的时候传入的,此处不在赘述;
需要去看WindowManager.addView的流程;
image.png

由于DecorView本身是一个FramLayout,所以他的Measure过程肯定会遵循View,ViewGroup和FramLayout的measure过程;

由于ViewGroup和FrameLayout都没有实现measure,所以只会执行View的measure方法;

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

View的默认onMeasure方法实现:

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

但是FrameLayout会复习这个方法:

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

因此方法会直接调用FrameLayout里面的onMeasure方法,并不会走到View里面的onMeasure方法;
FrameLayout首先执行了一个for循环,让他的每个子view都去执行measureChildWithMargin;
注释1处调用了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,又开始调用view的measure方法
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

从注释1可以看出,这个方法是viewGroup递归的开始,也就是
view.measure会调用view的onMeasure方法
---》如果view是一个ViewGroup的具体实现类,则会调用实现类的onMeasure,比如framlayout方法
---》实现类一般会使用for循环,去遍历子view
---》子view如果依旧是一个ViewGroup的实现类,则会继续调用子VIew的onMeasure,继续遍历子View的measure
---》直到子VIew不是一个ViewGroup类型,则调用子VIew的onMeasure方法完成测量

上面的measureChildWithMargins总共分成了2步;
1.通过父容器的MeasureSpec和子元素本身的LayoutParam决定子View的MeasureSpec
2.调用子view的measure方法;
通过这个递归,就会得到所有FramLayout所有子View的测量宽高,也就是mMeasuredWidth和mMeasuredHeight
最后就是比大小,由于FrameLayout的宽高是由所有子VIew中的最大宽和所有子view中的最大高决定的(当然还要考虑一下margin);
就得的了frameLayout自己的宽高,也就是DecorView的宽高;

在讨论ViewGroup的测量过程,是不能直接看ViewGroup的,因为ViewGroup毕竟是个抽象的,他不会直接实现onMeasure方法,他是把这个过程交给子类去实现的,由子类的for循环+viewgroup的measureChildWithMargins完成整个View树的测量,
为啥ViewGroup不自己实现呢,因为他也不知道自己的布局是啥样呀;

整个测量过程一定是父容器的MeasureSpec+自身的layoutParam一起,决定了自身的MeasureSpec,等自身的MeasureSpec确定了,就可以通过onMeasure方法去完成最终的测量,所有顶端的View就是DecorView,那么DecorView的父容器就只能从他的Window中去获取;

完成测量后,整个view树上的所有的view都会有两个测量值,mMeasuredWidth和mMeasuredHeight,通过setMeasuredDimensionRaw方法设置;这也是measure阶段的产出,供给layout使用的;

performLayout布局

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

传入的三个参数:
lp:window的layoutParam
mWidth:
mHeight:


image.png

此处的host就是DecorView

image.png

此处先通过setFrame设置了自身的属性;mLeft,mTop,mRight,mBottom

然后在调用view的onLayout方法,


image.png

可以看到这边是一个空实现,为啥会是空的呢,因为view自己的属性值刚刚已经通过setFrame方法自己设置了啊;

由于DecorView是一个FrameLayout,所有虽然不会View的onLayout为空,但是会执行
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);
            }
        }
    }

此处又是通过一个for循环,完成递归,可以看出来的是,每一个子view都是通过先确定子view的left和top,再根据测量宽高mMeasuredWidth和mMeasuredHeight,计算出他的right和bottom;
还是很容易理解的;

mMeasuredWidth:View的测量宽
mMeasuredHeight:View的测量高
getWidth():实际宽
getHeight():实际高


image.png

所有实际宽高是在layout产生的;

layout阶段作用根据测量阶段的宽高算出他的四个值,
mLeft,mTop,mRight,mBottom
而这四个值,又会对draw阶段产生实际影响

performDraw流程

明天继续

上一篇下一篇

猜你喜欢

热点阅读