上一篇咱們說到了View的建立,咱們先回顧一下,DecorView是應用窗口的根部View,咱們在View的建立簡單來講就是對DecorView對象的建立,而後將DecorView添加到咱們窗口Window對象中,在添加的過程裏,實際用到是實現WindowManager抽象類的WindowManagerImpl類WindowManagerImpl#addView方法,在addView方法中重要的兩段:javascript
root = new ViewRootImpl(view.getContext(),display);
root.setView(view,wparams,panelParentView);複製代碼
如代碼中所示,ViewRoot對應接口類ViewRootImpl,參數diaplay(Window類)、view(DecorView類)。
這兩段代碼的大概是,當DecorView對象被建立後,DecorView會被加入Window中,同時會建立ViewRootImpl對象,並將ViewRootImpl對象和DecorView創建關聯。ViewRootImpl則負責渲染視圖,最後WindowManagerService調用ViewRootImpl#performTraverals方法使得ViewTree開始進行View的測量、佈局、繪製工做。java
private void performTraversals() {
...
if (!mStopped) {
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
if (didLayout) {
performLayout(lp, desiredWindowWidth, desiredWindowHeight);
...
}
if (!cancelDraw && !newSurface) {
if (!skipDraw || mReportNextDraw) {
if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
for (int i = 0; i < mPendingTransitions.size(); ++i) {
mPendingTransitions.get(i).startChangingAnimations();
}
mPendingTransitions.clear();
}
performDraw();
}
}
...
}複製代碼
onMeasureandroid
看回ViewRootImpl#PerformTraveals代碼以前,咱們首先來了解一下MeasureSpec,MeasureSpec類是View類的一個內部類。註釋對MeasureSpec的描述翻譯是:MeasureSpc類封裝了父View傳遞給子View的佈局(layout)要求;每一個MeasureSpc實例表明寬度或者高度;MeasureSpec的值由大小與規格組成。ide
咱們看一下MeasureSpec的源碼:(必定要徹底清楚理解的點)佈局
public class View implements ... {
···
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;//移位位數爲30
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
//UNSPECIFIED(未指定),父元素不對子元素施加任何束縛,子元素能夠獲得任意想要的大小
//向右移位30位,其值爲00 + (30位0) , 即 0x0000(16進製表示)
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
//EXACTLY(精確),父元素決定子元素的確切大小,子元素將被限定在給定的邊界裏而忽略它自己大小;
//向右移位30位,其值爲01 + (30位0) , 即0x1000(16進製表示)
public static final int EXACTLY = 1 << MODE_SHIFT;
//AT_MOST(至多),子元素至多達到指定大小的值。
//向右移位30位,其值爲02 + (30位0) , 即0x2000(16進製表示)
public static final int AT_MOST = 2 << MODE_SHIFT;
public static int makeMeasureSpec(int size, int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
//將size和mode打包成一個32位的int型數值
//高2位表示SpecMode,測量模式,低30位表示SpecSize,某種測量模式下的規格大小
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
//將32位的MeasureSpec解包,返回SpecMode,測量模式
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
//將32位的MeasureSpec解包,返回SpecSize,某種測量模式下的規格大小
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
}
}複製代碼
從代碼看出MeasureSpec則保存了該View的尺寸規格。在View的測量流程中,經過makeMeasureSpec來保存大小規格信息,在其餘類經過getMode或getSize獲得模式和寬高。ui
可能有不少人想不通,一個int型整數怎麼能夠表示兩個東西(大小模式和大小的值),一個int類型咱們知道有32位。而模式有三種,要表示三種狀態,至少得2位二進制位。因而系統採用了最高的2位表示模式。如圖:this
在瞭解完MeasureSpec後,咱們終於能夠看回ViewRootImpl#PerformTraveals代碼了。看到getRootMeasureSpec()方法,從方法命名咱們瞭解到獲取根部的MeasureSpec,回想一下,MeasureSpec的第一條就說明父View傳遞給子View的佈局要求,而咱們如今是DecorView是根佈局了。那getRootMeasureSpec()方法到底是怎麼的呢?看ViewRootImpl#getRootMeasureSpec源碼:spa
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;
}複製代碼
方法中的參數windowSize表明是窗口的大小,rootDimension表明根部(DecorView)的尺寸。而DecorView是FrameLayout子類。故DecorView的MeasureSpec中的SpecSize爲窗口大小,SpecMode的EXACTLY。所以ViewRootImpl#PerformTraveals代碼中的childWidthMeasureSpec/childHeightMeasureSpec的值被賦值爲屏幕的尺寸。翻譯
如今咱們得到了DecorView的MeasureSpec。記住它表明着DecorView的尺寸和規格。接着是執行performMeasure()方法:3d
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}複製代碼
代碼很易懂,調用mView.measure。這裏mView是DecorView,我相信你們都能懂。還有DecorView是FrameLayout子類,FrameLayout繼承ViewGroup,那咱們去ViewGroup類看measure()方法,發現ViewGroup並無,那就去View看(ViewGroup繼承View)。終於找到了View#measure方法:(注意是final修飾符修飾,其不能被重載)
public class View implements ... {
···
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int oWidth = insets.left + insets.right;
int oHeight = insets.top + insets.bottom;
widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth);
heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
}
long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
resolveRtlPropertiesIfNeeded();
int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
mMeasureCache.indexOfKey(key);
if (cacheIndex < 0 || sIgnoreMeasureCache) {
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
} else {
long value = mMeasureCache.valueAt(cacheIndex);
setMeasuredDimensionRaw((int) (value >> 32), (int) value);
mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
throw new IllegalStateException("View with id " + getId() + ": "
+ getClass().getName() + "#onMeasure() did not set the"
+ " measured dimension by calling"
+ " setMeasuredDimension()");
}
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
(long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
}
}複製代碼
咱們把目光聚焦在onMeasure()方法,因爲子類繼承父類覆寫方法的緣由。咱們應該看到是DecorView#onMeasure,在該方法內部,主要是進行了一些判斷,這裏不展開來看了,到最後會調用到super.onMeasure方法,即FrameLayout#onMeasure方法。
因爲不一樣的ViewGroup,那麼它們的onMeasure()都是不同的。就好比咱們自定義View都覆寫onMeasure()。
那咱們分析FrameLayout#onMeasure,點進去看方法的實現:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//獲取當前佈局內的子View數量
int count = getChildCount();
//判斷當前佈局的寬高是不是match_parent模式或者指定一個精確的大小,若是是則置measureMatchParent爲false.
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
//遍歷全部類型不爲GONE的子View
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
//對每個子View進行測量
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//尋找子View中寬高的最大者,由於若是FrameLayout是wrap_content屬性
//那麼它的大小取決於子View中的最大者
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());
//若是FrameLayout是wrap_content模式,那麼往mMatchParentChildren中添加
//寬或者高爲match_parent的子View,由於該子View的最終測量大小會受到FrameLayout的最終測量大小影響
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());
}
//全部的子View測量以後,通過一系類的計算以後經過setMeasuredDimension設置本身的寬高
//對於FrameLayout可能用最大的子View的大小,對於LinearLayout,多是高度的累加。
//保存測量結果
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
//子View中設置爲match_parent的個數
count = mMatchParentChildren.size();
//只有FrameLayout的模式爲wrap_content的時候纔會執行下列語句
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
//對FrameLayout的寬度規格設置,由於這會影響子View的測量
final int childWidthMeasureSpec;
/** * 若是子View的寬度是match_parent屬性,那麼對當前子View的MeasureSpec修改: * 把widthMeasureSpec的寬度規格修改成:總寬度 - padding - margin,這樣作的意思是: * 對於子Viw來講,若是要match_parent,那麼它能夠覆蓋的範圍是FrameLayout的測量寬度 * 減去padding和margin後剩下的空間。 * * 如下兩點的結論,能夠查看getChildMeasureSpec()方法: * * 若是子View的寬度是一個肯定的值,好比50dp,那麼FrameLayout的widthMeasureSpec的寬度規格修改成: * SpecSize爲子View的寬度,即50dp,SpecMode爲EXACTLY模式 * * 若是子View的寬度是wrap_content屬性,那麼FrameLayout的widthMeasureSpec的寬度規格修改成: * SpecSize爲子View的寬度減去padding減去margin,SpecMode爲AT_MOST模式 */
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);
}
//對於這部分的子View須要從新進行measure過程
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}複製代碼
這部代碼很長,可是比較好理解,簡單總結下:首先,FrameLayout根據它的MeasureSpec來對每個子View進行測量,即調用measureChildWithMargin方法;對於每個測量完成的子View,會尋找其中最大的寬高,那麼FrameLayout的測量寬高會受到這個子View的最大寬高的影響(wrap_content模式),接着調用setMeasureDimension方法,把FrameLayout的測量寬高保存。
從一開始的ViewRootImpl#performTraversals中得到DecorView的尺寸,而後在performMeasure方法中開始測量流程,對於不一樣的layout佈局(ViewGroup)有着不一樣的實現方式,但大致上是在onMeasure方法中,對每個子View進行遍歷,根據ViewGroup的MeasureSpec及子View的layoutParams來肯定自身的測量寬高,而後最後根據全部子View的測量寬高信息再肯定父容器的測量寬高。那就是說要先完成對子View的測量再進行本身的測量。
那麼接着咱們繼續分析對子View是怎麼測量ViewGroup#measureChildWithMargins。
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
// 子View的LayoutParams,你在xml的layout_width和layout_height
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);
}複製代碼
從上面源碼可知,裏面主要使用了getChildMeasureSpec方法,將父容器的MeasureSpec和本身的layoutParams屬性(內外邊距和尺寸)傳遞進去來獲取子View的MeasureSpec。咱們看一下ViewGroup#getChildMeasureSpec方法:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
//計算子View可用空間大小
int size = Math.max(0, specSize - padding);
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY:
// 子View的width或height是個精確值
if (childDimension >= 0) {
// 表示子View的LayoutParams指定了具體大小值
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
//子View的width或height爲 MATCH_PARENT/FILL_PAREN
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
// 子View想和父View同樣大
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
//子View的width或height爲 WRAP_CONTENT
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
// 子View想本身決定其尺寸,但不能比父View大
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST:
···
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED:
···
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}複製代碼
由於分析DecorView我就只分析MeasureSpec.EXACTLY的,然而那部分代碼也很容易理解。總體來講就是根據不一樣的父容器的模式及子View的layoutParams來決定子View的規格尺寸模式。你們能夠根據下圖來理解MeasureSpec父View與子View之間的賦值規則。
在子View獲取到MeasureSpec後,返回到measureChildWithMargins方法中的childWidthMeasureSpec和
childHeightMeasureSpec值。接着代碼執行child.measure()方法。該方法的參數也是咱們剛剛獲取到的子View的MeasureSpec。你們還記得咱們上面分析的View#measure嗎?它是final方法,因此這裏的child.measure()方法就是調用回View#measure,這個View#measure方法的核心就是onMeasure(),若此時的子View爲ViewGroup的子類,便會調用相應容器類的onMeasure()方法,其餘容器ViewGroup的onMeasure()方法與FrameLayout的onMeasure()方法執行過程類似,都是要遞歸子View測量。那麼咱們先放一下不繼續分析,後面再回來講這個問題。
咱們回到FrameLayout的onMeasure()方法中,當遞歸執行完對子View的測量以後,會調用setMeasureDimension方法來保存測量結果,在上面的源碼裏面,該方法的參數接收的是resolveSizeAndState方法的返回值。View類的resolveSizeAndState()方法的源碼以下:
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
final int specMode = MeasureSpec.getMode(measureSpec);
final int specSize = MeasureSpec.getSize(measureSpec);
final int result;
switch (specMode) {
case MeasureSpec.AT_MOST:
if (specSize < size) {
// 父View給定的最大尺寸小於徹底顯示內容所需尺寸
// 則在測量結果上加上MEASURED_STATE_TOO_SMALL
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
// 若specMode爲EXACTLY,則不考慮size,result直接賦值爲specSize
result = specSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}複製代碼
上面的代碼較爲清晰易懂咱們就不重複講解。咱們總體來講,是先遞歸測量完子View,而後將計算的測量寬高保存。接着說回View的onMeasure()問題,以前咱們能夠看出View#measure方法是final修飾的,然而它的核心方法裏頭是onMeasure(),對於不一樣的View有着不一樣的實現方式,即便是咱們自定義View,也會調用View#onMeasure方法,因此咱們也看看它裏面的實現過程:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}複製代碼
源碼很清晰,這裏調用了setMeasureDimension方法,上面說過該方法的做用是設置測量寬高,而測量寬高則是從getDefaultSize中獲取,咱們繼續看看這個getDefaultSize()方法:
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
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;
}複製代碼
你們有沒感受代碼很類似,根據不一樣模式來設置不一樣的測量寬高,咱們直接看MeasureSpec.AT_MOST和MeasureSpec.EXACTLY模式,它直接把specSize返回了,即View在這兩種模式下的測量寬高直接取決於specSize規格。也便是說,對於一個直接繼承自View的自定義View來講,它的wrap_content和match_parent屬性的效果是同樣的,所以若是要實現自定義View的wrap_content,則要重寫onMeasure方法,對wrap_content屬性進行處理。
接着,咱們看UNSPECIFIED模式,這個模式可能比較少見,通常用於系統內部測量,它直接返回的是size,而不是specSize,那麼size從哪裏來的呢?再往上看一層,它來自於getSuggestedMinimumWidth()或getSuggestedMinimumHeight(),咱們選取其中一個方法,看看源碼,View#getSuggestedMinimumWidth:
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}複製代碼
當View沒有設置背景的時候,返回mMinWidth,該值對應於android:minWidth屬性;若是設置了背景,那麼返回mMinWidth和mBackground.getMinimumWidth中的最大值。那麼mBackground.getMinimumWidth又是什麼呢?其實它表明了背景的原始寬度,好比對於一個Bitmap來講,它的原始寬度就是圖片的尺寸。
咱們的View的測量就基本到這來了,咱們總結一下:測量從ViewRootImpl#performTraverals開始,首先獲取到DecorView根佈局的MeasureSpec,而後開始測量工做,經過不斷的遍歷子View的measure方法,根據ViewGroup的MeasureSpec及子View的LayoutParams來決定子View的MeasureSpec,進一步獲取子View的測量寬高,而後逐層返回,不斷保存ViewGroup的測量寬高。
咱們測量的工做完成了,咱們能夠看回ViewRootImpl#performTraverals方法,接着下一篇咱們是佈局工做。