【Android源碼】View的繪制流程

目錄:

目錄

一魏宽、問(wèn)題:

首先還是來(lái)看一種情況,我們?cè)贏ctivity的三個(gè)地方查看View的measureHeight屬性决乎,因?yàn)橹挥衜easure后的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())
}

我們?cè)倏匆幌耹og

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屬性,這就說(shuō)明范嘱,在onCreate方法和onResume方法執(zhí)行時(shí)送膳,我們的View都還沒(méi)被measure

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

之前我們分析過(guò)肠缨,setContentView的源碼逆趋,為了看仔細(xì)一點(diǎn),我們選擇看繼承Avtivity的setContentView的源碼晒奕,而Activity里面的setContentView是調(diào)用的PhoneWindow的setContentView闻书,所以PhoneWindow的setContentView

public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        //創(chuàng)建DecorView和mContentParent
        //并將我們系統(tǒng)的布局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只是創(chuàng)建了DecorView并把我們的布局添加到了DecorView上,但是還沒(méi)有調(diào)用onMeasure方法脑慧。

我們?cè)購(gòu)腁ctivity的啟動(dòng)流程入手魄眉,對(duì)于ActivityThread里面的performLaunchActivity方法,它里面通過(guò)反射調(diào)用了Activity的onCreate方法

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

而ActivityThread的handleResumeActivity方法闷袒,他里面調(diào)用了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里面調(diào)用了performResume坑律,這里才去執(zhí)行了我們Activity的onResume方法,

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

handleResumeActivity方法里面調(diào)用完performResumeActivity之后囊骤,才調(diào)用的wm.addView(decor, l);晃择,,他是從這里才把DecorView加載到ViewManager里面也物,這時(shí)才開(kāi)始View的繪制流程:measure() -> layout() -> draw()

所以宫屠,這里就解釋了,為什么我們?cè)趏nCreate()和onResume()里面獲取不到View的measureHeight屬性滑蚯,就是因?yàn)閛nCreate和obResume方法執(zhí)行的時(shí)候浪蹂,View的繪制還沒(méi)開(kāi)始。而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進(jìn)來(lái)之后斥赋,他是調(diào)用的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];
        }
        //入隊(duì)列
        mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
        mCount++;
    }
}

post進(jìn)來(lái)之后的cation會(huì)保存進(jìn)隊(duì)列中缰猴,但是沒(méi)有執(zhí)行,而是在View的dispatchAttachedToWindow方法中執(zhí)行疤剑,而dispatchAttachedToWindow方法就是在測(cè)量完畢之后才調(diào)用的

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    //...
    // Transfer all pending runnables.
    if (mRunQueue != null) {
        //里面是個(gè)for循環(huán)洛波,去執(zhí)行隊(duì)列中的全部Action
        mRunQueue.executeActions(info.mHandler);
        mRunQueue = null;
    }
}

所以,到了這里骚露,我們也就基本解釋清楚了蹬挤,為什么onCreate、onResume和View.post里面獲取View的measureHeight屬性出現(xiàn)的情況了棘幸。

四焰扳、總結(jié)(過(guò)程展示)

執(zhí)行過(guò)程:

image-20201013162709179.png

五、WindowManagerImpl

當(dāng)我們調(diào)用Activity的startActivity()時(shí),最終會(huì)調(diào)用ActivityThread的handleLaunchActivity()方法來(lái)創(chuàng)建Activity的

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
    //...
    //創(chuàng)建Activity吨悍,這里面會(huì)調(diào)用到Activity的onCreate()方法(通過(guò)反射)
    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) {
    //創(chuàng)建Activity
    activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
    //初始化時(shí)已經(jīng)創(chuàng)建好了扫茅,這里只是獲得
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    //調(diào)用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);
    //調(diào)用Activity的onCreate()方法
    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}

執(zhí)行完handleLaunchActivity(),就會(huì)繼續(xù)去執(zhí)行handleResumeActivity()方法

我們?cè)贏ctivityThread的handleResumeActivity()方法中育瓜,看到了他內(nèi)部調(diào)用了ViewManager的addView()和updateViewLayout()的方法葫隙,而ViewManager的這兩個(gè)方法是在他的實(shí)現(xiàn)類WindowManagerImpl里面實(shí)現(xiàn)的

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    //...
    //這里面回去調(diào)用Activity的onResume()方法
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    //...
    ViewManager wm = a.getWindowManager();
    //把decorView傳進(jìn)了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) {
    //調(diào)用Activity的onResume()方法
     r.activity.performResume(r.startsNotResumed, reason);
}

我們進(jìn)到WindowManagerImpl類中,他調(diào)用的是mGlobal的方法

private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    //此時(shí)的view(DecorView繼續(xù)被傳遞)
    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);
}

再往里面進(jìn)去

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

    //這里的View就是外面?zhèn)鬟M(jìn)來(lái)的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 {
        //**重點(diǎn)**恋脚,這里把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;
    }
}

從這里我們發(fā)現(xiàn)一個(gè)事情焰手,我們以前一直以為DecorView就是PhoneWindow下面的根布局糟描,但是從這里,我們可以看到书妻,DecorView也是加到ViewRootImpl上面的root.setView(view, wparams, panelParentView, userId);

雖然DecorView被加載到了PhoneWindow上船响,但是此時(shí)界面仍然沒(méi)有什么顯示,因?yàn)閂iew的工作流程還沒(méi)有執(zhí)行完躲履,還需要經(jīng)過(guò)measure见间、layout、draw過(guò)程

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();
    }
}
//上面這個(gè)類的實(shí)例化對(duì)象
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

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

終于工猜,我們追到了performTraversals()方法米诉,網(wǎng)上很多文章,也就是從這里開(kāi)始講的

六域慷、重點(diǎn):View的繪制流程

//root.setView(view, wparams, panelParentView);   使DecorView加載到了PhoneWindow上荒辕,但是不可見(jiàn)
//performTraversals()  這個(gè)方法使ViewTree開(kāi)始View的工作流程汗销,讓DecorView上面的東西開(kāi)始展示出來(lái)
private void performTraversals() {
    getRunQueue().executeActions(mAttachInfo.mHandler);
    //...
    //根據(jù)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();
}

//第一個(gè)參數(shù)是window的大小
//所以弛针,對(duì)于DecorView來(lái)說(shuō)叠骑,她的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來(lái)所茧跋,其并沒(méi)有父容器慰丛,那么他的MeasureSpec是怎么得來(lái)的呢?瘾杭?诅病??

對(duì)于DecorView來(lái)說(shuō),她的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
        //調(diào)用View里面的onMeasure方法蝇棉,測(cè)量開(kāi)始
        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;
    }
}

這個(gè)方法里面調(diào)用了onMeasure方法,而此時(shí)onMeasure測(cè)量的是我們的根布局DecorView方法芥永,測(cè)量了DecorView后篡殷,我們又會(huì)用onMeasure測(cè)量我們布局的根布局

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) {
        //返回外面?zhèn)鬟M(jìn)來(lái)的getDefaultSize()
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        //說(shuō)明wrap_content和match_parent屬性的效果是一樣的
        //因此,在實(shí)現(xiàn)自定義View的warp_content時(shí)埋涧,需要重寫onMeasure
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
    }
    return result;
}

//根據(jù)是否設(shè)置背景來(lái)確定返回值
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方法里面,調(diào)用了setMeasuredDimension()飞袋,它里面主要是用來(lái)設(shè)置View的寬高的戳气。

而在傳參數(shù)到setMeasuredDimension()時(shí),還調(diào)用了getDefaultSize()方法對(duì)其進(jìn)行處理巧鸭,而它里面則是根據(jù)MeasureSpec的Mode來(lái)返回不同的值瓶您。

對(duì)于UNSPECIFIED模式,直接返回外面?zhèn)鬟M(jìn)來(lái)的返回外面?zhèn)鬟M(jìn)來(lái)的getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec)值纲仍。而getSuggestedMinimumWidth()方法是根據(jù)用戶是否設(shè)置了View的background來(lái)確定其返回值的呀袱。如果沒(méi)有背景,則返回mMinWidth值郑叠,mMinWidth是可以在外部設(shè)置的夜赵,可以是Android:minWidth也可以是view.setMinimumWidth()來(lái)設(shè)置。如果設(shè)置了背景乡革,則取mMinWidthmBackground.getMinimumWidth()的最大值作為返回值寇僧,由于mBackground是Drawable對(duì)象,所以在Drawable的源碼里面查看getMinimumWidth()的實(shí)現(xiàn)沸版。

由于AT_MOST模式和EXACTLY是一樣的嘁傀,所以在實(shí)現(xiàn)自定義View的warp_content時(shí)候,需要重寫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;
    //通過(guò)for循環(huán)去拿我們里面的子布局
    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            mTotalLength += measureNullChild(i);
            continue;
        }
        //把每個(gè)子View的高度加起來(lái)并賦值給mTotalLength
        mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
        measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
                        heightMeasureSpec, usedHeight);
    }
    //測(cè)完子View细办,還得加上LinearLayout的Padding屬性
    mTotalLength += mPaddingTop + mPaddingBottom;
    //測(cè)量完之后,接著調(diào)用這個(gè)方法蕾殴,我們的布局才有了真正的寬和高笑撞,這里進(jìn)去是給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);
    //通過(guò)調(diào)用子View的onMeasure方法,去測(cè)量子View的寬高钓觉,這里的兩個(gè)參數(shù)childXXXMeasureSpec都是父布局已經(jīng)給我們測(cè)量好了的
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

ViewGroup.java里面查看測(cè)量的方式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;
    //根據(jù)父布局的模式去給子View的resultSize茴肥、resultMode賦值
    switch (specMode) {
        // Parent has imposed an exact size on us
        //當(dāng)父布局是match_parent、fill_parent(Deprecated)荡灾、明確的值
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {//當(dāng)ViewGroup中的子view是設(shè)置了具體大小的值時(shí)( X dp)
                //子View的大小就等于設(shè)置的子View的大小
                resultSize = childDimension;
                //mode就是EXACTLY
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//如果子View外面設(shè)置的大小是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
        //當(dāng)父布局是warp_content時(shí)
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                //子View被設(shè)置成了明確的值瓤狐,那么他的模式直接就是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;
                //當(dāng)父布局是AT_MOST模式時(shí),即使子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);
}

【注】:

當(dāng)父布局是AT_MOST模式時(shí)赦政,即使子View是MATCH_PARENT,他的模式耀怜,最終還是AT_MOST恢着,所以,子View的mode是父布局的mode和自己一起決定的

調(diào)用完measure方法之后财破,就會(huì)調(diào)用setMeasuredDimension()方法掰派,這個(gè)時(shí)候我們的布局才真正指定寬度和高度,measuredWidth和measuredHeight才真正有值

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    //通過(guò)for循環(huán)去拿我們里面的子布局
    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (childWeight > 0) {
            //記錄所有子View的高左痢,方便計(jì)算自己的高靡羡,這里我們看的是Vertical方向的LinearLayout,所以他只是計(jì)算的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);
            //去測(cè)量子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);
    }
    //測(cè)量完之后俊性,接著調(diào)用這個(gè)方法略步,我們的布局才有了真正的寬和高,這里進(jìn)去是給measuredWidth和measuredHeight賦值
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);
}

總結(jié):

測(cè)量都是從外往里遞歸定页,他先會(huì)把ViewRootImpl的測(cè)量模式傳到DecorView趟薄,然后DecorView再把測(cè)量模式傳到我們的根布局,依次向底部傳典徊,然后杭煎,最底層的View會(huì)拿子View的寬高來(lái)計(jì)算自己的寬高,依次向外傳

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是一個(gè)空方法卒落,因?yàn)闆](méi)有一個(gè)統(tǒng)一的樣式羡铲,所以留給自定義View自己去實(shí)現(xiàn)

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

2)ViewGroup的onLayout()方法

走到這里,基本的步驟流程差不多定好了导绷,我們?nèi)タ淳唧w的View中是怎么實(shí)現(xiàn)的犀勒,還是用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
    //計(jì)算父窗口推薦的子View寬度
    final int width = right - left;
    //計(jì)算父窗口推薦的子View右側(cè)位置
    int childRight = width - mPaddingRight;

    // Space available for child
    //child可使用空間大小
    int childSpace = width - paddingLeft - mPaddingRight;
    //通過(guò)ViewGroup的getChildCount方法獲取ViewGroup的子View個(gè)數(shù)
    final int count = getVirtualChildCount();
    //獲取Gravity屬性設(shè)置
    final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
    final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
    //依據(jù)majorGravity計(jì)算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;
    }
    //重點(diǎn)J浩M浊!開(kāi)始遍歷
    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過(guò)程來(lái)決定的钦购,因此measure過(guò)程的意義就是為layout過(guò)程提供視圖顯示范圍的參考值
            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);
            //依據(jù)不同的absoluteGravity計(jì)算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;
            //通過(guò)垂直排列計(jì)算調(diào)運(yùn)child的layout設(shè)置child的位置
            setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                          childWidth, childHeight);
            childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

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

總結(jié):

layout也是從頂層父View向子View的遞歸調(diào)用view.layout方法的過(guò)程檐盟,即父View根據(jù)第一步performMeasure,來(lái)獲取子View所的布局大小和布局參數(shù)押桃,將子View放在合適的位置上葵萎,==不過(guò)這個(gè)方法沒(méi)有再往外走,只是不斷的往里面走==。

3.繪制流程第三步performDraw

1)View的draw()方法

View的draw流程很簡(jiǎn)單羡忘,官方指定了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:保存當(dāng)前camvas層
*      3. Draw view's content:繪制View的內(nèi)容
*      4. Draw children:繪制子View
*      5. If necessary, draw the fading edges and restore layers:如果需要,則繪制View的褪色邊緣卷雕,這類似于陰影效果
*      6. Draw decorations (scrollbars for instance):繪制裝飾节猿,比如滾動(dòng)條
*/

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的繪制流程其實(shí)就三個(gè)步驟:onMeasure(測(cè)量) -> onLayout(擺放) -> onDraw(繪制)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市漫雕,隨后出現(xiàn)的幾起案子滨嘱,更是在濱河造成了極大的恐慌,老刑警劉巖浸间,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件太雨,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡魁蒜,警方通過(guò)查閱死者的電腦和手機(jī)囊扳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)兜看,“玉大人宪拥,你說(shuō)我怎么就攤上這事∠臣酰” “怎么了她君?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)葫哗。 經(jīng)常有香客問(wèn)我缔刹,道長(zhǎng),這世上最難降的妖魔是什么劣针? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任校镐,我火速辦了婚禮,結(jié)果婚禮上捺典,老公的妹妹穿的比我還像新娘鸟廓。我一直安慰自己,他們只是感情好襟己,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布引谜。 她就那樣靜靜地躺著,像睡著了一般擎浴。 火紅的嫁衣襯著肌膚如雪员咽。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,578評(píng)論 1 305
  • 那天贮预,我揣著相機(jī)與錄音贝室,去河邊找鬼契讲。 笑死,一個(gè)胖子當(dāng)著我的面吹牛滑频,可吹牛的內(nèi)容都是我干的捡偏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼峡迷,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼霹琼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起凉当,我...
    開(kāi)封第一講書(shū)人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤枣申,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后看杭,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體忠藤,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年楼雹,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了模孩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡贮缅,死狀恐怖榨咐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谴供,我是刑警寧澤块茁,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站桂肌,受9級(jí)特大地震影響数焊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜崎场,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一佩耳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谭跨,春花似錦干厚、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至污呼,卻和暖如春裕坊,著一層夾襖步出監(jiān)牢的瞬間包竹,已是汗流浹背燕酷。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工籍凝, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人苗缩。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓饵蒂,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親酱讶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子退盯,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容