上一篇咱们说到了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方法,接着下一篇咱们是布局工做。