View測(cè)量、布局、繪制流程
在Activity啟動(dòng)時(shí),執(zhí)行AcitivtyThread.handleResumeActivity()方法時(shí),會(huì)調(diào)用ActivityClientRecord.activity.makeVisible()悉盆,在方法是在執(zhí)行Activity.onResume之后才執(zhí)行的,從Activity.makeVisible()到View的測(cè)量馋吗、布局焕盟、繪制的流程如下:
ActivityThread.handleResumeActivity();
Activity.makeVisible(); //執(zhí)行Activity.onResume之后,再執(zhí)行makeVisible宏粤;
ViewManager.addView(DecorView...)//DecorView是根布局脚翘,后續(xù)會(huì)用到
WindowManagerImpl.addView();//ViewManager是一個(gè)接口,真正實(shí)現(xiàn)在WindowManagerImpl中绍哎;
WindowManagerGlobal.addView();//WindowManagerImple并沒有實(shí)現(xiàn)WIndow三大操作来农,而是全部交給WindowManagerGlobal來處理;
ViewRootImpl.setView(view, wparams, panelParentView);// 將傳進(jìn)來的參數(shù)DecorView設(shè)置到root中崇堰。參數(shù)view就是DecorView
ViewRootImpl.requestLayout();
ViewRootImpl.scheduleTraversals();
ViewRootImpl.doTraversal();
ViewRootImpl.performTraversals();
ViewRootImpl.performMeasure() performLayout() performDraw();//在performTraversals中調(diào)用測(cè)量沃于、布局财搁、繪制操作坟桅;
WindowManagerGlobal.addView()方法:
WindowManagerGlobal
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
// 1棒厘、檢查參數(shù)是否合法
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (display == null) {
throw new IllegalArgumentException("display must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
// 2粹胯、創(chuàng)建ViewRootImpl并將View添加到列表中。這里每次都會(huì)new一個(gè)ViewRootImpl對(duì)象咨演,
// 所以說調(diào)用一次addView闸昨,就會(huì)有一個(gè)ViewRootImpl,也可以理解為一個(gè)Activity就會(huì)創(chuàng)建一個(gè)ViewRootImpl
ViewRootImpl root;
View panelParentView = null;
// 獲得ViewRootImpl對(duì)象root
// ViewRoot相當(dāng)于是MVC模型中的Controller,它有以下職責(zé):
// 1. 負(fù)責(zé)為應(yīng)用程序窗口視圖創(chuàng)建Surface薄风。
// 2. 配合WindowManagerService來管理系統(tǒng)的應(yīng)用程序窗口零院。
// 3. 負(fù)責(zé)管理、布局和渲染應(yīng)用程序窗口視圖的UI村刨。
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
// addView時(shí)會(huì)將相關(guān)對(duì)象添加到對(duì)應(yīng)集合中,存儲(chǔ)這些ViewRootImpl, View, LayoutParam
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
// do this last because it fires off messages to start doing things
try {
// 3撰茎、通過ViewRootImpl來更新界面并顯示在窗口上嵌牺,完成Window的添加過程
// 將傳進(jìn)來的參數(shù)DecorView設(shè)置到root中。參數(shù)view就是DecorView
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
}
}
}
說明:
(1)參數(shù)view就是根View(DecorView)龄糊;
(2)Window是以view的形式存在逆粹,Android中所有視圖都是通過Window來呈現(xiàn)的,View是Android中視圖呈現(xiàn)的方式炫惩;
(3)Window有三種類型:分別是應(yīng)用Window(對(duì)應(yīng)著一個(gè)Activity)僻弹、子Window(附屬在特定Window之上,例如Dialog)和系統(tǒng)Window(Toast和系統(tǒng)狀態(tài)欄)他嚷;
(4)一個(gè)Activity對(duì)應(yīng)一個(gè)Window蹋绽,一個(gè)Window對(duì)應(yīng)著一個(gè)ViewRootImpl,可以通過adb shell dumpsys meminfo 可以在Objects中看到Activity個(gè)數(shù)和ViewRootImpl個(gè)數(shù)筋蓖;如下圖所示:
ViewRootImpl.setView()方法:
ViewRootImpl類:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
// 將頂層視圖DecorView賦值給全局的mView卸耘,后續(xù)測(cè)量、布局粘咖、繪制都是從根View(mView)開始的
mView = view;
// 通過requestLayout來完成異步刷新請(qǐng)求蚣抗,requestLayout最終會(huì)調(diào)用performTraversals方法來完成View的繪制
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
// 當(dāng)窗口沒有按鍵事件傳輸通道時(shí),創(chuàng)建一個(gè)InputChannel對(duì)象瓮下,相當(dāng)于一個(gè)管道翰铡,
// 其他進(jìn)程通過該管道向窗口發(fā)送按鍵事件消息
mInputChannel = new InputChannel();
}
// 接著會(huì)通過WindowSession最終來完成Window的添加過程
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
// 2、調(diào)用mWindowSession添加View
// 通過Binder調(diào)用讽坏,進(jìn)入system_server進(jìn)程的Session.
// mWindowSession的類型是IWindowSession锭魔,它是一個(gè)Binder對(duì)象,
// 真正的實(shí)現(xiàn)類是Session路呜,這也就是之前提到的IPC調(diào)用的位置赂毯。
// 在Session內(nèi)部會(huì)通過WindowManagerService來實(shí)現(xiàn)Window的添加
// WMS與APP交互的接口通過WindowState的IWindow
// mInputChannel:待注冊(cè)的管道對(duì)象
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = new InputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
// 輸入事件從Native傳到Java層最先調(diào)用WindowInputReceiver.onInputEvent()方法
mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}
}
}
}
相關(guān)方法調(diào)用順序?yàn)椋簉equestLayout()>scheduleTraversals()>doTraversal(),其中doTraversal會(huì)調(diào)用到ViewRootImpl.performTraversals()方法,在performTraversals()方法開始View的測(cè)量、布局党涕、繪制工作烦感;measure過程決定了View的寬高、Measure完之后膛堤,可以通過getMeasureWidth和getMeasureHeight獲取View的測(cè)量寬高手趣,幾乎所有情況它們都等于View的最終寬高;Layout過程決定了View的四個(gè)頂點(diǎn)坐標(biāo)和實(shí)際的View的寬高肥荔,可以通過getTop绿渣、getBottom、getLeft燕耿、getRight得到View的四個(gè)頂點(diǎn)位置中符,通過getWidth、getHeigt獲取View的最終寬高誉帅,Draw過程決定了View的顯示淀散,只有draw完成之后View的內(nèi)容才會(huì)顯示在屏幕上。
ViewRootImpl類:
private void performTraversals() {
// cache mView since it is used so much below...
// mView就是DecorView根布局
final View host = mView;
if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
|| mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
updatedConfiguration) {
// 根據(jù)Activity窗口的當(dāng)前寬(高)度和寬(高)度測(cè)量規(guī)范來計(jì)算得到它的頂層視圖DecorView
// 的寬度測(cè)量規(guī)范childWidthMeasureSpec和高度測(cè)量規(guī)范childHeightMeasureSpec蚜锨。
// mWidth和mHeight表示窗口的寬高档插,lp.width和lp.height表示DecorView根布局寬和高,
// 在創(chuàng)建ViewGroup實(shí)例時(shí)等于MATCH_PARENT
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// 執(zhí)行測(cè)量操作
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
}
// 執(zhí)行布局操作
performLayout(lp, mWidth, mHeight);
// 執(zhí)行繪制操作
performDraw();
}
理解MeasureSpec
(1)View.MeasureSpec:32位int值亚再,高兩位SpecMode(測(cè)量模式)郭膛,低30位SpecSize(測(cè)量值);系統(tǒng)通過MeasureSpec對(duì)View進(jìn)行測(cè)量氛悬;
(2)測(cè)量模式有三種:
UNSPECIFIED:未指定模式则剃,View想多大就多大,父容器不做限制如捅,一般用于系統(tǒng)內(nèi)部的測(cè)量忍级。
AT_MOST:最大模式,父容器指定了一個(gè)可用大小即SpecSize伪朽,View的大小不能大于這個(gè)值轴咱,具體是什么值要看不同View的具體實(shí)現(xiàn),他對(duì)應(yīng)于LayoutParams中的wrap_content烈涮;
EXACTLY:精確模式朴肺,父容器已經(jīng)檢測(cè)出View所需的精確大小,這時(shí)候VIew的最終大小就是SpecSize所指定的值坚洽,它對(duì)應(yīng)于LayoutParams中的match_parent和具體的數(shù)值兩種模式戈稿;
(3)MeasureSpec由View的layoutParams和父容器一起決定;根View(DecorVIew)和普通View有區(qū)別:DecorView由窗口尺寸和其自身的layoutParams決定讶舰;普通View由父容器和自身layoutParams來決定鞍盗;確定MeasureSpec就知道View的測(cè)量大行枇恕;
(4)DecorView創(chuàng)建過程在ViewRootImple的measureHieraychy中調(diào)用getRootMeasureSpec(desiredWindowWidth, lp.width)般甲,其中desiredWindowWidth是當(dāng)前Window的大小(向上追代碼可以確定就是Window的大小)肋乍,lp.width是DecorView的layoutParams中的寬度;(lp.width從onresume的wm.addView方法開始將該DecorView的參數(shù)傳遞下來)敷存,這樣DecorView的MeasureSpec就確定下來了墓造。
ViewRootImpl類:
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
//匹配父容器時(shí),測(cè)量模式為MeasureSpec.EXACTLY锚烦,測(cè)量大小直接為屏幕的大小觅闽,也就是充滿整個(gè)屏幕
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
//包裹內(nèi)容時(shí),測(cè)量模式為MeasureSpec.AT_MOST涮俄,測(cè)量大小直接為屏幕大小蛉拙,也就是充滿整個(gè)屏幕
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
//其他情況時(shí),測(cè)量模式為MeasureSpec.EXACTLY彻亲,測(cè)量大小為DecorView頂層視圖布局設(shè)置的大小
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
(5)普通View的MeasureSpec:最終會(huì)調(diào)用到ViewGroup.measuresChildWIthMargins()孕锄,然后調(diào)用
getChildMeasureSpec(spec,padding,childDimens)其中padding是父容器已經(jīng)占用的空間,ViewGroup.measuresChildWIthMargins()方法如下:
ViewGroup類:
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) {
// Parent has imposed an exact size on us
//父View是精確模式
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
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
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
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;
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);
}
通過以上源碼可以得到表中的結(jié)論睹栖;
通過上表可以看出,只要提供父容器的MeasureSpec和子元素的LayoutParams茧痕,就可以快速確定出子元素的MeasureSpec野来,有了MeasureSpec就可以確定出子View的測(cè)量后的大小。
View的工作過程:主要是指View的測(cè)量踪旷、布局曼氛、繪制三大流程,這三大流程都從從根View(DecorView)開始的令野。measure確定view的寬高舀患、layout確定view的最終寬高和四個(gè)頂點(diǎn)位置、draw將View繪制到屏幕上气破。
測(cè)量過程
對(duì)于原始View聊浅,通過measure方法就完成了其測(cè)量過程;但是對(duì)于ViewGroup除了完成自己的測(cè)量過程外现使,還會(huì)遍歷去調(diào)用所有子元素的measure方法低匙,各個(gè)子元素再遞歸去執(zhí)行measure流程;
View的measure過程
View的測(cè)量是從根View(DecorView)開始的碳锈,在ViewRootImpl.performTraversals()方法中調(diào)用performMeasure開始View的測(cè)量流程
ViewRootImpl類:
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
其中mView就是DecorView顽冶,在setViews方法中會(huì)將DecorView賦值給mView;繼續(xù)執(zhí)行mView.measure()方法
View類:
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
if (forceLayout || needsLayout) {
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
// 調(diào)用了onMeasure方法進(jìn)行測(cè)量售碳,說明View主要的測(cè)量邏輯是在該方法中實(shí)現(xiàn)强重。
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;
}
}
}
View的measure方法是final類型绞呈,所以無法重寫,在measure中會(huì)調(diào)用onmeasure间景,onmeasure方法可以重寫佃声,會(huì)繼續(xù)執(zhí)行DecorView的onMeasure,在DecorView中會(huì)調(diào)用super.onMeasure,由于DecorView繼承Framelayou,所以會(huì)繼續(xù)執(zhí)行FrameLayout.onMeasure方法拱燃;下一步我們?cè)诜治鯲iewGroup.onMeasure秉溉;我們先繼續(xù)分析View.onMeasure方法;
View類:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
在View.onMeasure中會(huì)調(diào)用setMeasureDimension方法設(shè)置View的測(cè)量寬高碗誉,我們只需要看getDefaultSize即可
View類:
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
//獲得測(cè)量模式
int specMode = MeasureSpec.getMode(measureSpec);
//獲得父親容器留給子視圖View的大小
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
getDefaultSize根據(jù)View布局設(shè)置的寬高和父View傳遞的測(cè)量規(guī)格MeasureSpec計(jì)算出View的測(cè)量寬高召嘶。我們只要看AT_MOST和EXACTLY這兩種情況,這兩種情況的返回大致就是MeasureSpec中的specSize值哮缺,這個(gè)specSize就是View測(cè)量后的大小弄跌。
View測(cè)量過程主要工作:根據(jù)View的MeasureSpec得到View的測(cè)量大小,然后調(diào)用setMeasureDimension設(shè)置view的測(cè)量寬高尝苇,并且測(cè)量工作最先從根View(DecorView)開始铛只;
ViewGroup measure過程
對(duì)于ViewGroup的measure過程除了完成自己的Measure過程,還需要遍歷去調(diào)用所有子元素的measure方法糠溜,各個(gè)子元素再遞歸執(zhí)行這個(gè)過程淳玩。在View的測(cè)量過程中我們已經(jīng)從DecorView.measure方法開始執(zhí)行到了FrameLayout.onMeasure,我們繼續(xù)來看ViewGroup的onMeasure方法非竿;
FrameLayout類:
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) {
//測(cè)量FrameLayout下每個(gè)子視圖View的寬和高
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);
}
}
}
}
//設(shè)置當(dāng)前FrameLayout測(cè)量結(jié)果蜕着,此方法的調(diào)用表示當(dāng)前View測(cè)量的結(jié)束
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
}
在FrameLayout.onMeasure中會(huì)調(diào)用measureChildWithMargins方法去遍歷調(diào)用每個(gè)子元素的Measure方法,這樣各個(gè)子元素的就進(jìn)入了Measure過程红柱,在子元素測(cè)量完畢后承匣,會(huì)根據(jù)子元素的情況來測(cè)量自己的大小。調(diào)用resolveSizeAndState來獲取自身的測(cè)量寬高锤悄。
ViewGroup.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);
}
在該方法中主要子View做了兩件事韧骗,首先根據(jù)父View的MeasureSpec和自身的布局參數(shù)得到子View的MeasureSpec,然后調(diào)用子VIew自己的Measure方法零聚;這樣一個(gè)個(gè)子View就完成了測(cè)量過程袍暴;
View的測(cè)量過程是三大流程中最復(fù)雜的一個(gè),measure測(cè)量完成后隶症,就可以獲取到View的測(cè)量寬高容诬,在某些極端情況下,系統(tǒng)需要多次測(cè)量才可能確定最終的測(cè)量寬高沿腰,這種情況下onMeasure中拿到的寬高很可能不準(zhǔn)確览徒,最好是在onLayout總?cè)カ@取View的測(cè)量寬高。同時(shí)在oncreate颂龙、onstart习蓬、onresume獲取不到準(zhǔn)確的測(cè)量寬高纽什,因?yàn)閂iew的測(cè)量流程是在onResume之后。
以上介紹了ViewRootImpl.performTraversals中performMeasure方法躲叼,在performMeasure中首先從根View(DecorView)開始執(zhí)行Measure過程芦缰,然后分別介紹了View和ViewGroup的測(cè)量過程。
布局過程
Layout過程從ViewRootImpl.performTraversals中的performLayout方法開始枫慷,即從DecorView開始让蕾。Layout作用是ViewGroup用來確定子View的位置,當(dāng)ViewGroup位置被確定之后或听,再onLayout中遍歷所以自己元素探孝,并調(diào)用其Layout方法,在layout方法中onLayout又會(huì)被調(diào)用誉裆,layout過程和Measure過程相比比較簡(jiǎn)單顿颅,layout方法確定View自身的位置,onLayout確定所有子View的位置足丢。我們從看ViewRootImpl.performLayout方法:
ViewRootImpl類:
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
// mView就是DecorView
final View host = mView;
try {
// DecorView請(qǐng)求布局粱腻。DecorView的四個(gè)位置左=0,頂=0斩跌,右=屏幕寬绍些,底=屏幕高,說明DecorView布局的位置是從
// 屏幕最左最頂端開始布局耀鸦,到屏幕最低最右結(jié)束柬批。因此DecorView根布局是充滿整個(gè)屏幕的
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
...
}
mInLayout = false;
}
mView就是DecorView,host.layout方法會(huì)調(diào)用View.layout方法揭糕;
View類:
public void layout(int l, int t, int r, int b) {
//判斷是否需要重新測(cè)量
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
//保存上一次View的四個(gè)位置
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
//設(shè)置當(dāng)前視圖View的左萝快,頂锻霎,右著角,底的位置,并且判斷布局是否有改變
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
//如果布局有改變旋恼,條件成立吏口,則視圖View重新布局
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//調(diào)用onLayout,將具體布局邏輯留給子類實(shí)現(xiàn)
onLayout(changed, l, t, r, b);
}
...
}
在layout方法中會(huì)調(diào)用setFrame方法來設(shè)置View的四個(gè)頂點(diǎn)位置冰更,即初始化mLeft产徊、mRight、mTop蜀细、mBottom.View的四個(gè)頂點(diǎn)確定之后那么在父容器中的位置就確定了舟铜。接著調(diào)用onLayou方法,在該方法中確定子元素的位置奠衔。我們接著來看FrameLayout.onLayout方法谆刨;
FrameLayout類:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//給子視圖View進(jìn)行布局
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();
//遍歷當(dāng)前FrameLayout下的子View
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
//當(dāng)子視圖View可見度設(shè)置為GONE時(shí)塘娶,不進(jìn)行當(dāng)前子視圖View的布局,這就是為什么當(dāng)你布局中使用Visibility=GONE時(shí)痊夭,該view是不占據(jù)空間的
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//獲得子視圖View的寬高
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;
//以下代碼獲得子視圖View的四個(gè)位置刁岸,用于子視圖View布局
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;
}
//調(diào)用子元素的布局過程
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
其中,當(dāng)子視圖View可見度設(shè)置為GONE時(shí)她我,不進(jìn)行當(dāng)前子視圖View的布局虹曙,這就是為什么當(dāng)你布局中使用Visibility=GONE時(shí),該view是不占據(jù)空間的番舆。
在ViewRootImpl.performlayou方法中首先調(diào)用DecorView的layou方法確定DecorView自身的位置酝碳,然后再調(diào)用DeocrView的onLayout方法所以子元素的位置。
繪制過程
Draw過程比較簡(jiǎn)單合蔽,它的作用是將View繪制到屏幕上击敌。Draw過程從ViewRootImpl.performTraversals中的performDraw方法開始,即從DecorView開始拴事。從performDraw到DecorView.draw方法流程如下:
ViewRootImpl.performDraw();
ViewRootImple.Draw();
DecorView.draw();
View.Draw();
在ViewRootImpl.draw方法中會(huì)調(diào)用mView.draw()沃斤,mView就是DecorView;我們來看View.draw方法:
public void draw(Canvas canvas) {
/*
* 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
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
* 1.繪制當(dāng)前視圖的背景
* 2.保存當(dāng)前畫布的堆棧狀態(tài)刃宵,并且在當(dāng)前畫布上創(chuàng)建額外的圖層衡瓶,以便在Step5繪制當(dāng)前視圖在滑動(dòng)時(shí)的邊框漸變效果
* 3.繪制當(dāng)前視圖的內(nèi)容
* 4.繪制當(dāng)前視圖的子視圖的內(nèi)容
* 5.繪制當(dāng)前視圖在滑動(dòng)時(shí)的邊框漸變效果
* 6.繪制當(dāng)前視圖的滾動(dòng)條。
*/
// Step 1, draw the background, if needed
// Step1:繪制視圖View的背景
if (!dirtyOpaque) {
drawBackground(canvas);
}
// Step 3, draw the content 繪制自己
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children 調(diào)用diapatchDraw繪制子元素
dispatchDraw(canvas);
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
}
View.onDraw主要工作:調(diào)用drawBackground(canvas)繪制自己的背景牲证,
調(diào)用onDraw繪制自己哮针;調(diào)用dipatchDraw繪制所有子元素;繪制裝飾等等坦袍;View的繪制傳遞是通過dispatchDraw來實(shí)現(xiàn)的十厢,dispatchDraw會(huì)遍歷調(diào)用所有子元素的Draw,這樣draw一層層的傳遞下去捂齐,最終完成所有View的繪制蛮放;
View測(cè)量、布局奠宜、繪制流程總結(jié)
View的測(cè)量布局繪制工作是從ViewRootImpl.performTraversals方法開始包颁,分別調(diào)用調(diào)用performMeasure、performLayout压真、performDraw方法開始測(cè)量布局繪制工作娩嚼,測(cè)量布局繪制工作都是從根View(DecorView)開始,然后一層層傳遞下去滴肿,最終完成所有View測(cè)量布局繪制工作岳悟;