【Android源码】View的绘制流程

目录:

目录

一、问题:

首先还是来看一种情况,我们在Activity的三个地方查看View的measureHeight属性,因为只有measure后的View才具有measureHeight属性,否则为0,

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    mHandle = Handler(Looper.getMainLooper())

    Log.d("MainActivity", "onCreate btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())

    btn_view.post {
        Log.d("MainActivity", "post btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())
    }
}
override fun onResume() {
    super.onResume()
    Log.d("MainActivity", "onResume btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())
}

我们再看一下log

2020-10-13 10:22:26.067 22953-22953/? D/MainActivity: onCreate btn_view.measuredHeight ==> 0
2020-10-13 10:22:26.074 22953-22953/? D/MainActivity: onResume btn_view.measuredHeight ==> 0
2020-10-13 10:22:26.233 22953-22953/? D/MainActivity: post btn_view.measuredHeight ==> 144

这里显示,只有View.post()里面,才打印出了View的measureHeight属性,这就说明,在onCreate方法和onResume方法执行时,我们的View都还没被measure

二、onCreate()方法、onResume()方法

之前我们分析过,setContentView的源码,为了看仔细一点,我们选择看继承Avtivity的setContentView的源码,而Activity里面的setContentView是调用的PhoneWindow的setContentView,所以PhoneWindow的setContentView

public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        //创建DecorView和mContentParent
        //并将我们系统的布局android.R.layout.content添加到了mDecor上
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    //...
}

这里的setContent只是创建了DecorView并把我们的布局添加到了DecorView上,但是还没有调用onMeasure方法。

我们再从Activity的启动流程入手,对于ActivityThread里面的performLaunchActivity方法,它里面通过反射调用了Activity的onCreate方法

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //...
    activity = mInstrumentation.newActivity(
        cl, component.getClassName(), r.intent);
    //...
}

而ActivityThread的handleResumeActivity方法,他里面调用了performResumeActivity方法

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    //...
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    //...
    if (r.window == null && !a.mFinished && willBeVisible) {
            ViewManager wm = a.getWindowManager();
            //...
            View decor = r.window.getDecorView();
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    wm.addView(decor, l);
                } 
            }
        } 
        if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
            //...
            if ((l.softInputMode
                    & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                    != forwardBit) {
                if (r.activity.mVisibleFromClient) {
                    ViewManager wm = a.getWindowManager();
                    View decor = r.window.getDecorView();
                    wm.updateViewLayout(decor, l);
                }
            }
            if (r.activity.mVisibleFromClient) {
                r.activity.makeVisible();
            }
        }
}

performResumeActivity里面调用了performResume,这里才去执行了我们Activity的onResume方法,

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {
    try {
        r.activity.performResume(r.startsNotResumed, reason);
    }catch (Exception e) {
        //...
    }
}

handleResumeActivity方法里面调用完performResumeActivity之后,才调用的wm.addView(decor, l);,,他是从这里才把DecorView加载到ViewManager里面,这时才开始View的绘制流程:measure() -> layout() -> draw()

所以,这里就解释了,为什么我们在onCreate()和onResume()里面获取不到View的measureHeight属性,就是因为onCreate和obResume方法执行的时候,View的绘制还没开始。而View.post()里面为什么就可以了呢?

三、View.post()方法

我们看一下View.post的源码

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

这里可以看到,post进来之后,他是调用的HandlerActionQueue.java类里面的post方法

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

post进来之后的cation会保存进队列中,但是没有执行,而是在View的dispatchAttachedToWindow方法中执行,而dispatchAttachedToWindow方法就是在测量完毕之后才调用的

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    //...
    // Transfer all pending runnables.
    if (mRunQueue != null) {
        //里面是个for循环,去执行队列中的全部Action
        mRunQueue.executeActions(info.mHandler);
        mRunQueue = null;
    }
}

所以,到了这里,我们也就基本解释清楚了,为什么onCreate、onResume和View.post里面获取View的measureHeight属性出现的情况了。

四、总结(过程展示)

执行过程:

image-20201013162709179.png

五、WindowManagerImpl

当我们调用Activity的startActivity()时,最终会调用ActivityThread的handleLaunchActivity()方法来创建Activity的

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
    //...
    //创建Activity,这里面会调用到Activity的onCreate()方法(通过反射)
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } 
    //...
    return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //创建Activity
    activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
    //初始化时已经创建好了,这里只是获得
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    //调用Activity的attch方法
    activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
    //调用Activity的onCreate()方法
    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}

执行完handleLaunchActivity(),就会继续去执行handleResumeActivity()方法

我们在ActivityThread的handleResumeActivity()方法中,看到了他内部调用了ViewManager的addView()和updateViewLayout()的方法,而ViewManager的这两个方法是在他的实现类WindowManagerImpl里面实现的

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    //...
    //这里面回去调用Activity的onResume()方法
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    //...
    ViewManager wm = a.getWindowManager();
    //把decorView传进了addView和updateViewLayout里面了
    View decor = r.window.getDecorView();
    decor.setVisibility(View.INVISIBLE);
    ViewManager wm = a.getWindowManager();
    if(){
        wm.addView(decor, l);
    }else{
        wm.updateViewLayout(decor, l);
    }
}

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
    String reason) {
    //调用Activity的onResume()方法
     r.activity.performResume(r.startsNotResumed, reason);
}

我们进到WindowManagerImpl类中,他调用的是mGlobal的方法

private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    //此时的view(DecorView继续被传递)
    mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
            mContext.getUserId());
}

@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    mGlobal.updateViewLayout(view, params);
}

再往里面进去

public void addView(View view, ViewGroup.LayoutParams params,
        Display display, Window parentWindow, int userId) {
    //...
    ViewRootImpl root;
    View panelParentView = null;
    //实例化了ViewRootImpl的对象root
    root = new ViewRootImpl(view.getContext(), display);

    //这里的View就是外面传进来的DecorView,
    view.setLayoutParams(wparams);
    mViews.add(view);
    mRoots.add(root);
    mParams.add(wparams);
    // do this last because it fires off messages to start doing things
    try {
        //**重点**,这里把DecorView加到了ViewRootImpl上,即把DecorView加载到了PhoneWindow上
        root.setView(view, wparams, panelParentView, userId);
    } catch (RuntimeException e) {
        // BadTokenException or InvalidDisplayException, clean up.
        if (index >= 0) {
            removeViewLocked(index, true);
        }
        throw e;
    }
}

从这里我们发现一个事情,我们以前一直以为DecorView就是PhoneWindow下面的根布局,但是从这里,我们可以看到,DecorView也是加到ViewRootImpl上面的root.setView(view, wparams, panelParentView, userId);

虽然DecorView被加载到了PhoneWindow上,但是此时界面仍然没有什么显示,因为View的工作流程还没有执行完,还需要经过measure、layout、draw过程

ViewRootImpl.java

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

public void requestLayout() {
    //...
    scheduleTraversals();
}

void scheduleTraversals() {
    //...
    mChoreographer.postCallback(
            Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
    //...
}


final class TraversalRunnable implements Runnable {
    @Override
    public void run() {
        doTraversal();
    }
}
//上面这个类的实例化对象
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

void doTraversal() {
    //...
    performTraversals();
    //...
}

终于,我们追到了performTraversals()方法,网上很多文章,也就是从这里开始讲的

六、重点:View的绘制流程

//root.setView(view, wparams, panelParentView);   使DecorView加载到了PhoneWindow上,但是不可见
//performTraversals()  这个方法使ViewTree开始View的工作流程,让DecorView上面的东西开始展示出来
private void performTraversals() {
    getRunQueue().executeActions(mAttachInfo.mHandler);
    //...
    //根据DecorView自身的LayoutParams,和WindowSize去获取DecorView的MeasureSpec,然后传给performMeasure()方法
    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    //...
    performLayout(lp, mWidth, mHeight);
    //...
    performDraw();
}

//第一个参数是window的大小
//所以,对于DecorView来说,她的Measure是由他自身的LayoutParams和Window的大小决定的。这和一般的View不同
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.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
    }
    return measureSpec;
}

思考?

MeasureSpec是收自身的LayoutParams和父容器的MeasureSpec共同影响的。那么,作为顶层View的DecorView来所,其并没有父容器,那么他的MeasureSpec是怎么得来的呢????

对于DecorView来说,她的Measure是由他自身的LayoutParams和Window的大小决定的。这和一般的View不同

1. 绘制流程第一步performMeasure

ViewRootImpl.java

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

在View.java中查看measure方法

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    if (cacheIndex < 0 || sIgnoreMeasureCache) {
        // measure ourselves, this should set the measured dimension flag back
        //调用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方法,而此时onMeasure测量的是我们的根布局DecorView方法,测量了DecorView后,我们又会用onMeasure测量我们布局的根布局

1)View的onMeasure()方法

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

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
        //返回外面传进来的getDefaultSize()
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        //说明wrap_content和match_parent属性的效果是一样的
        //因此,在实现自定义View的warp_content时,需要重写onMeasure
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
    }
    return result;
}

//根据是否设置背景来确定返回值
protected int getSuggestedMinimumWidth() {
    return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

//Drawable.java
public int getMinimumWidth() {
    //得到Drawable的固有宽度
    final int intrinsicWidth = getIntrinsicWidth();
    //宽度大于0则返回,否则返回0
    return intrinsicWidth > 0 ? intrinsicWidth : 0;
}

在View的onMeasure方法里面,调用了setMeasuredDimension(),它里面主要是用来设置View的宽高的。

而在传参数到setMeasuredDimension()时,还调用了getDefaultSize()方法对其进行处理,而它里面则是根据MeasureSpec的Mode来返回不同的值。

对于UNSPECIFIED模式,直接返回外面传进来的返回外面传进来的getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec)值。而getSuggestedMinimumWidth()方法是根据用户是否设置了View的background来确定其返回值的。如果没有背景,则返回mMinWidth值,mMinWidth是可以在外部设置的,可以是Android:minWidth也可以是view.setMinimumWidth()来设置。如果设置了背景,则取mMinWidthmBackground.getMinimumWidth()的最大值作为返回值,由于mBackground是Drawable对象,所以在Drawable的源码里面查看getMinimumWidth()的实现。

由于AT_MOST模式和EXACTLY是一样的,所以在实现自定义View的warp_content时候,需要重写onMeasure,下面是模板代码:

private int measureWidth(int measureSpec){
    int result = 0;
    int mode = MeasureSpec.getMode(measureSpec);
    int size = MeasureSpec.getSize(measureSpec);

    if (mode == MeasureSpec.EXACTLY){//精确模式
        result = size;
    }else{//AT_MOST或UNSPECIFIED
        result = 200;
        if (mode == MeasureSpec.AT_MOST){//最小值
            result = Math.min(result,size);
        }
    }
    return result;
}

2)ViewGroup的onMeasure()方法

(这里以LinearLayout为例)

LinearLayout.java

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //首先判断的是orientation
    if (mOrientation == VERTICAL) {
        measureVertical(widthMeasureSpec, heightMeasureSpec);
    } else {
        measureHorizontal(widthMeasureSpec, heightMeasureSpec);
    }
}

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    //记录垂直方向的高度
    mTotalLength = 0;
    //通过for循环去拿我们里面的子布局
    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            mTotalLength += measureNullChild(i);
            continue;
        }
        //把每个子View的高度加起来并赋值给mTotalLength
        mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
        measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
                        heightMeasureSpec, usedHeight);
    }
    //测完子View,还得加上LinearLayout的Padding属性
    mTotalLength += mPaddingTop + mPaddingBottom;
    //测量完之后,接着调用这个方法,我们的布局才有了真正的宽和高,这里进去是给measuredWidth和measuredHeight赋值
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);
}

void measureChildBeforeLayout(View child, int childIndex,
            int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
            int totalHeight) {
    measureChildWithMargins(child, widthMeasureSpec, totalWidth,
                            heightMeasureSpec, totalHeight);
}

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);
    //通过调用子View的onMeasure方法,去测量子View的宽高,这里的两个参数childXXXMeasureSpec都是父布局已经给我们测量好了的
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

ViewGroup.java里面查看测量的方式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;
    //根据父布局的模式去给子View的resultSize、resultMode赋值
    switch (specMode) {
        // Parent has imposed an exact size on us
        //当父布局是match_parent、fill_parent(Deprecated)、明确的值
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {//当ViewGroup中的子view是设置了具体大小的值时( X dp)
                //子View的大小就等于设置的子View的大小
                resultSize = childDimension;
                //mode就是EXACTLY
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//如果子View外面设置的大小是MATCH_PARENT
                // Child wants to be our size. So be it.
                //子View的大小就等于父布局的大小
                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;

        // Parent has imposed a maximum size on us
        //当父布局是warp_content时
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                //子View被设置成了明确的值,那么他的模式直接就是EXACTLY,不受父布局的影响
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                //当父布局是AT_MOST模式时,即使子View是MATCH_PARENT,他的模式,最终还是AT_MOST,所以,子View的mode是父布局的mode和自己一起决定的
                resultMode = MeasureSpec.AT_MOST;
            } 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;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
    }
    //noinspection ResourceType
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

【注】:

当父布局是AT_MOST模式时,即使子View是MATCH_PARENT,他的模式,最终还是AT_MOST,所以,子View的mode是父布局的mode和自己一起决定的

调用完measure方法之后,就会调用setMeasuredDimension()方法,这个时候我们的布局才真正指定宽度和高度,measuredWidth和measuredHeight才真正有值

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    //通过for循环去拿我们里面的子布局
    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (childWeight > 0) {
            //记录所有子View的高,方便计算自己的高,这里我们看的是Vertical方向的LinearLayout,所以他只是计算的Height
            if (mUseLargestChild && heightMode != MeasureSpec.EXACTLY) {
                childHeight = largestChildHeight;
            } else if (lp.height == 0 && (!mAllowInconsistentMeasurement
                    || heightMode == MeasureSpec.EXACTLY)) {
                childHeight = share;
            } else {
                childHeight = child.getMeasuredHeight() + share;
            }
            final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                    Math.max(0, childHeight), MeasureSpec.EXACTLY);
            final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                    mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin,
                    lp.width);
            //去测量子View
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            // Child may now not fit in vertical dimension.
            childState = combineMeasuredStates(childState, child.getMeasuredState()
                    & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
        }
        measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
                        heightMeasureSpec, usedHeight);
    }
    //测量完之后,接着调用这个方法,我们的布局才有了真正的宽和高,这里进去是给measuredWidth和measuredHeight赋值
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);
}

总结:

测量都是从外往里递归,他先会把ViewRootImpl的测量模式传到DecorView,然后DecorView再把测量模式传到我们的根布局,依次向底部传,然后,最底层的View会拿子View的宽高来计算自己的宽高,依次向外传

image-20201013215655174.png

2. 绘制流程第二步performLayout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
        int desiredWindowHeight) {
    final View host = mView;
    try {
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
    }
}

public void layout(int l, int t, int r, int b) {
    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
        onLayout(changed, l, t, r, b);
    }
}

1)View的onLayout()方法

View的onLayout是一个空方法,因为没有一个统一的样式,所以留给自定义View自己去实现

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

2)ViewGroup的onLayout()方法

走到这里,基本的步骤流程差不多定好了,我们去看具体的View中是怎么实现的,还是用LinearLayout举例

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (mOrientation == VERTICAL) {
        layoutVertical(l, t, r, b);
    } else {
        layoutHorizontal(l, t, r, b);
    }
}

void layoutVertical(int left, int top, int right, int bottom) {
    final int paddingLeft = mPaddingLeft;

    int childTop;
    int childLeft;

    // Where right end of child should go
    //计算父窗口推荐的子View宽度
    final int width = right - left;
    //计算父窗口推荐的子View右侧位置
    int childRight = width - mPaddingRight;

    // Space available for child
    //child可使用空间大小
    int childSpace = width - paddingLeft - mPaddingRight;
    //通过ViewGroup的getChildCount方法获取ViewGroup的子View个数
    final int count = getVirtualChildCount();
    //获取Gravity属性设置
    final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
    final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
    //依据majorGravity计算childTop的位置值
    switch (majorGravity) {
        case Gravity.BOTTOM:
            // mTotalLength contains the padding already
            childTop = mPaddingTop + bottom - top - mTotalLength;
            break;

            // mTotalLength contains the padding already
        case Gravity.CENTER_VERTICAL:
            childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
            break;

        case Gravity.TOP:
        default:
            childTop = mPaddingTop;
            break;
    }
    //重点!!!开始遍历
    for (int i = 0; i < count; i++) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            childTop += measureNullChild(i);
        } else if (child.getVisibility() != GONE) {
            //LinearLayout中其子视图显示的宽和高由measure过程来决定的,因此measure过程的意义就是为layout过程提供视图显示范围的参考值
            final int childWidth = child.getMeasuredWidth();
            final int childHeight = child.getMeasuredHeight();
            //获取子View的LayoutParams
            final LinearLayout.LayoutParams lp =
                (LinearLayout.LayoutParams) child.getLayoutParams();

            int gravity = lp.gravity;
            if (gravity < 0) {
                gravity = minorGravity;
            }
            final int layoutDirection = getLayoutDirection();
            final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
            //依据不同的absoluteGravity计算childLeft位置
            switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    childLeft = paddingLeft + ((childSpace - childWidth) / 2)
                        + lp.leftMargin - lp.rightMargin;
                    break;

                case Gravity.RIGHT:
                    childLeft = childRight - childWidth - lp.rightMargin;
                    break;

                case Gravity.LEFT:
                default:
                    childLeft = paddingLeft + lp.leftMargin;
                    break;
            }

            if (hasDividerBeforeChildAt(i)) {
                childTop += mDividerHeight;
            }

            childTop += lp.topMargin;
            //通过垂直排列计算调运child的layout设置child的位置
            setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                          childWidth, childHeight);
            childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

            i += getChildrenSkipCount(child, i);
        }
    }
}

总结:

layout也是从顶层父View向子View的递归调用view.layout方法的过程,即父View根据第一步performMeasure,来获取子View所的布局大小和布局参数,将子View放在合适的位置上,==不过这个方法没有再往外走,只是不断的往里面走==。

3.绘制流程第三步performDraw

1)View的draw()方法

View的draw流程很简单,官方指定了6步

/*
* 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:保存当前camvas层
*      3. Draw view's content:绘制View的内容
*      4. Draw children:绘制子View
*      5. If necessary, draw the fading edges and restore layers:如果需要,则绘制View的褪色边缘,这类似于阴影效果
*      6. Draw decorations (scrollbars for instance):绘制装饰,比如滚动条
*/

2)ViewGroup的draw()方法

performDraw和上面的流程类似

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

private void draw(boolean fullRedrawNeeded) {
    Surface surface = mSurface;
    if (!surface.isValid()) {
        return;
    }

    if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
        return;
    }
}

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
                             boolean scalingRequired, Rect dirty) {
    // Draw with software renderer.
    final Canvas canvas;
    final int left = dirty.left;
    final int top = dirty.top;
    final int right = dirty.right;
    final int bottom = dirty.bottom;
    canvas = mSurface.lockCanvas(dirty);
    // ... ...
    mView.draw(canvas);
}

View的绘制流程其实就三个步骤:onMeasure(测量) -> onLayout(摆放) -> onDraw(绘制)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容