由于测量是一个从上到下的过程,而在这个过程中,父容器有必要告诉子View
它的一些绘制要求,那么这时候就须要依赖一个信使,来传递这个要求,它就是MeasureSpec
. MeasureSpec
是一个32
位的int
类型,咱们把它分为高2
位和低30
位。 其中高2
位表示mode
,它的取值为:bash
UNSPECIFIED(0) : The parent has not imposed any constraint on the child. It can be whatever size it wants.
EXACTLY(1) : The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be.
AT_MOST(2) : The child can be as large as it wants up to the specified size.
低30
位表示具体的size
。less
MeasureSpec
是父容器传递给子View
的宽高要求,并非说它传递的size
是多大,子View
最终就是多大,它是根据**父容器的MeasureSpec
和子View
的LayoutParams
**共同计算出来的。ide
为了更好的理解上面这段话,咱们须要借助ViewGroup
中的两个函数:函数
measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
getChildMeasureSpec(int spec, int padding, int childDimension)
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);
}
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) {
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
复制代码
能够看到,在调用getChildMeasureSpec
以前,须要考虑parent
和child
之间的间距,这包括parent
的padding
和child
的margin
,所以,参与传递给child
的MeasureSpec
的参数要考虑这么几方面:布局
measureSpec
和padding
View
的height
和widht
以及margin
。下面咱们来分析getChildMeasureSpec
的具体流程,它对宽高的处理逻辑都是相同的,根据父容器measureSpec
的mode
,分红如下几种状况:ui
mode
为EXACTLY
这种状况下说明父容器的大小已经肯定了,就是固定的值。this
View
指定了大小 那么子View
的mode
就是EXACTLY
,size
就是布局里面的值,这里就有疑问了,子View
所指定的宽高大于父容器的宽高怎么办呢?,咱们先留着这个疑问。View
为MATCH_PARENT
子View
但愿和父容器同样大,由于父容器的大小是肯定的,因此子View
的大小也是肯定的,size
就是父容器measureSpec
的size
- 父容器的padding
- 子View``margin
。View
为WRAP_CONTENT
子容器只要求可以包裹本身的内容,可是这时候它又不知道它所包裹的内容究竟是多大,那么这时候它就指定本身的大小就不能超过父容器的大小,因此mode
为AT_MOST
,size
和上面相似。mode
为AT_MOST
在这种状况下,父容器说明了本身最多不能超过多大,数值在measureSpec
的size
当中:spa
View
指定大小 同上分析。View
为MATCH_PARENT
子View
但愿和父容器同样大,而此时父容器只知道本身不能超过多大,所以子View
也就只能知道本身不能超过多大,因此它的mode
为AT_MOST
,size
就是父容器measureSpec
的size
- 父容器的padding
- 子View``margin
。View
为WRAP_CONTENT
子容器只要求可以包裹本身的内容,可是这时候它又不知道它所包裹的内容究竟是多大,这时候虽然父容器没有指定大小,可是它指定了最多不能超过多少,这时候子View
也不能超过这个值,因此mode
为AT_MOST
,size
的计算和上面相似。mode
为UNSPECIFIED
View
指定大小 同上分析。View
为MATCH_PARENT
子View
但愿和父容器同样大,可是这时候父容器并无约束,因此子View
也是没有约束的,因此它的mode
也为UNSPECIFIED
,size
的计算和以前一致。View
为WRAP_CONTENT
子View
不知道它包裹的内容多大,而且父容器是没有约束的,那么也只能为UNSPECIFIED
了,size
的计算和以前一致。performTraversals()
介绍完了基础的知识,咱们来从起点来整个看一下从View
树的根节点到叶节点的整个测量的过程。 咱们先直接说明结论,整个测量的起点是在ViewRootImpl
的performTraversals()
当中:code
private void performTraversals() {
......
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
//...
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
复制代码
上面的mView
是经过setView(View view, WindowManager.LayoutParams attrs, View panelParentView)
传进来的,那么这个view
是何时传递进来的呢? 如今回忆一下,在ActivityThread
的handleResumeActivity
中,咱们调用了ViewManager.add(mDecorView, xxx)
,而这个方法最终会调用到WindowManagerGlobal
的下面这个方法:orm
public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) {
root = new ViewRootImpl(view.getContext(), display);
}
//....
root.setView(view, wparams, panelParentView);
}
复制代码
也就是说,上面的**mView
也就是咱们在setContentView
当中渲染出来的mDecorView
**,也就是说它是整个View
树的根节点,由于mDecorView
是一个FrameLayout
,因此它调用的是FrameLayout
的measure
方法。 那么这整个从根节点遍历完整个View
树的过程是怎么实现的呢? 它其实就是依赖于measure
和onMeasure
:
View
,measure
是在它里面定义的,并且它是一个final
方法,所以它的全部子类都没有办法重写该方法,在该方法当中,会调用onMeasure
来设置最终测量的结果,对于View
来讲,它只是简单的取出父容器传进来的要求来设置,并无复杂的逻辑。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);
}
// Suppress sign extension for the low bytes
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) {
// first clears the measured dimension flag
mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
resolveRtlPropertiesIfNeeded();
int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
mMeasureCache.indexOfKey(key);
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
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;
}
// flag not set, setMeasuredDimension() was not invoked, we raise
// an exception to warn the developer
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
}
复制代码
ViewGroup
,因为它是View
的子类,所以它不可能重写measure
方法,而且它也没有重写onMeasure
方法。View
的控件,例如TextView
,它会重写onMeasure
,与View#onMeasure
不一样的是,它会考虑更多的状况来决定最终的测量结果。ViewGroup
的控件,例如FrameLayout
,它一样会重写onMeasure
方法,与继承于View
的控件不一样的是,因为ViewGroup
可能会有子View
,所以它在设置本身最终的测量结果以前,还有一个重要的任务:调用子View
的measure
方法,来对子View
进行测量,并根据子View
的结果来决定本身的大小。所以,整个从上到下的测量,其实就是一个View
树节点的遍历过程,每一个节点的onMeasure
返回时,就标志它的测量结束了,而这整个的过程是以View
中measure
方法为纽带的:
mDecorView
这个根节点的measure
方法,也就是performTraversals
中的那句话。ViewGroup
的控件,那么在它的onMeasure
方法中,它并不会直接调用子节点的onMeasure
方法,而是经过调用子节点measure
方法,因为子节点不可能重写View#measure
方法,所以它最终是经过View#measure
来调用子节点重写的onMeasure
来进行测量,子节点再在其中进行响应的逻辑处理。onMeausre
方法被调用时,它须要设置好本身的测量结果就好了。对于measure
和onMeasure
的区别,咱们能够用一句简单的话来总结一下:measure
负责进行测量的传递,onMeasure
负责测量的具体实现。
onMeasure
当中的setMeasuredDimension
上面咱们讲到设置的测量结果,其实测量过程的最终目的是:经过调用setMeasuredDimension
方法来给mMeasureHeight
和mMeasureWidth
赋值。 只要上面这个过程完成了,那么该ViewGroup/View/及其实现类
的测量也就结束了,而**setMeasuredDimension
必须在onMeasure
当中调用,不然会抛出异常**,因此咱们观察全部继承于ViewGroup/View
的控件,都会发现它们最后都是调用上面说的那个方法。 前面咱们已经分析过,measure
只是传递的纽带,所以它的逻辑是固定的,咱们直接看各个类的onMeasure
方法就好。
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) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
复制代码
这里,咱们会根据前面所说的,父容器传递进来measureSpec
中的mode
来给这两个变量赋值:
mode
为UNSPECIFIED
,那么说明父容器并不期望多个,所以子View
根据本身的背景或者minHeight/minWidth
属性来给本身赋值。AT_MOST
或者EXACTLY
,那么就把它设置为父容器指定的size
。ViewGroup
的onMeasure
因为ViewGroup
的目的是为了容纳各子View
,可是它并不肯定子View
应当如何排列,也就不知道该如何测量本身,所以它的onMeasure
是没有任何意义的,因此并无重写,而是应当由继承于它的控件来重写该方法。
ViewGroup
控件的onMeasure
为了方面,咱们以DecorView
为例,通过前面的分析,咱们知道当咱们在performTraversals
中调用它的measure
方法时,最终会回调到它对应的控件类型,也就是FrameLayout
的onMeasure
方法:
@Override
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) {
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);
}
}
}
}
// 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()); } setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); count = mMatchParentChildren.size(); if (count > 1) { for (int i = 0; i < count; i++) { final View child = mMatchParentChildren.get(i); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec; 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); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } 复制代码
咱们能够看到,整个的onMeasure
其实分为三步:
View
,调用measureChildWithMargins
进行第一次子View
的测量,在第一节中,咱们也分析了这个方法,它最终也是调用子View
的measure
方法。setMeasuredDimension
来设置本身的测量结果。View
,根据第二步的结果,调用child.measure
进行第二次的测量。这也验证了第二节中的结论:父容器和子View
的关联是经过measure
进行关联的。 同时咱们也能够有一个新的结论,对于View
树的某个节点,它的测量结果有可能并非一次决定的,这是因为父容器可能须要依赖于子View
的测量结果,而父容器的结果又可能会影响子View
,可是,咱们须要保证这个过程不是无限调用的。