前言
一 View的测量
首先回到ViewRootImpl#performTraversals函数:
private void performTraversals() {
if (!mStopped || mReportNextDraw) {
boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
(relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
|| mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
updatedConfiguration) {
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// 测量操作
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
//................
}
}
} else {
//................
}
//................
}
if (didLayout) {
//定位
performLayout(lp, mWidth, mHeight);
//................
}
//................
//绘制
performDraw();
//................
}
继续查看performMeasure函数:
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
//mView就是DecorView,从顶级View开始了测量流程
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
说明,在这里我需要看下childWidthMeasureSpe,childHeightMeasureSpec形参是怎么来的,如下:
//获取宽高的测量规格
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
那么getRootMeasureSpec是??
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
// 如果View的高宽属性为match_parent那么它的mode将会是EXACTLY
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// 如果View的高宽属性为 wrap_conent 那么它的mode将会是 AT_MOST
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// 如果View的高宽属性为具体数值那么它的mode将会是 EXACTLY
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
说明,在这里我门看到了一个对象MeasureSpec,MeasureSpec的作用是在在Measure流程中,系统将View的LayoutParams根据父容器所施加的规则转换成对应的MeasureSpec(规格),然后在onMeasure中根据这个MeasureSpec来确定view的测量宽高。同时可以从函数可以看出:
(1).如果View的属性为match_parent|确定值,那么它对应的mode为exactly;
(2).如果View的属性为wrap_parent,那么它对应的mode为at_most;
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/** @hide */
@IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
@Retention(RetentionPolicy.SOURCE)
public @interface MeasureSpecMode {}
/**
* UNSPECIFIED 模式:
* 父View不对子View有任何限制,子View需要多大就多大。
* 其值左位移30位:00 000000000000000000000000000000(32个0,前两位表示mode,后30位表示size)*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* EXACTYLY 模式:
* 父View已经测量出子Viwe所需要的精确大小,这时候View的最终大小
* 就是SpecSize所指定的值,对应于match_parent和精确数值这两种模式。
* 其值左位移30位:01 000000000000000000000000000000(32个0,前两位表示mode,后30位表示size)
* */
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* AT_MOST 模式:
* View的大小不能超过父View给定的specSize的大小,对应wrap_content这种模式。
* 其值左位移30位:10 000000000000000000000000000000(32个0,前两位表示mode,后30位表示size)
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
/**
* 包装一个测量规格
* @param size the size of the measure specification
* @param mode the mode of the measure specification
* @return the measure specification based on size and mode
*/
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
/**
* 生成一个安全的测量规格
* Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
* will automatically get a size of 0. Older apps expect this.
*
* @hide internal use only for compatibility with system widgets and older apps
*/
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
/**
* 从规格中解析出mode,其实就是得到32位中的前两位数值
* Extracts the mode from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the mode from
* @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
* {@link android.view.View.MeasureSpec#AT_MOST} or
* {@link android.view.View.MeasureSpec#EXACTLY}
*/
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
/**
* 从规格中解析出size,其实就是得到32位中的后30位数值
* Extracts the size from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the size from
* @return the size in pixels defined in the supplied measure specification
*/
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
static int adjust(int measureSpec, int delta) {
final int mode = getMode(measureSpec);
int size = getSize(measureSpec);
if (mode == UNSPECIFIED) {
// No need to adjust size for UNSPECIFIED mode.
return makeMeasureSpec(size, UNSPECIFIED);
}
size += delta;
if (size < 0) {
Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
") spec: " + toString(measureSpec) + " delta: " + delta);
size = 0;
}
return makeMeasureSpec(size, mode);
}
}
说明,那么在此处我们可以看到, 在出我们测量方法当中他传递的并不是一个纯粹的size,而是遵循了我们设置宽高时的几种模式:EXACTLY ,ATMOST ,UNSPECIFIED这三个模式的本质是0,1,2的左位移30位,那么其实我们先能理解为我们实际上在传递值得过程当中将显示模式mode+size打包一起交给measure方法,而里面的数据结构其实实际上是一个32位的数值,我们可以明显看到几个模式的值在后面进行了左位移操作了30位,用MODE_SHIFT 操作之后,实际表明一个32位的值30,前两位作为MODE,而MODE_MASK 表示是后30位,后30位为size。
具体如何运算的查看《MeasureSpec详解》。
继续查看VIew#measure函数:
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);
}
//........
if (forceLayout || needsLayout) {
// first clears the measured dimension flag
mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
resolveRtlPropertiesIfNeeded();
int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// 核心就在这里,调用了onMeasure方法,不管是LinearLayout或者是FreamLayout还是其他布局,
// 他们都是通过测量组件,实现我们的布局定位,每一个Layout的onMeasure实现都不一样.
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;
}
//........
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
//........
}
接下来,我们以FramLayout为例,查看onMeasure方法:
/**
* 该方法需要自己实现,在这个方法处理测量子view的业务
* @param widthMeasureSpec 父View 宽度规格
* @param heightMeasureSpec 父View 高度规格
*/
@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 为View集合,当FrameLayout的高宽属性为wrap_content,用来记录高宽属性为match_content的子View。
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) {
//TODO 1.对每一个子View进行测量,最终还是会调用measure方法
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);
}
}
}
}
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());
}
//TODO 2.保存测量结果,其中调用了resolveSizeAndState函数
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
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();
//子View的宽度测量规格
final int childWidthMeasureSpec;
/**
* 如果子View的宽度是match_parent属性,那么view的可用宽度将会是FrameLayout的测量宽度
* 减去padding和margin后剩下的空间。
*/
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 {
/* TODO 3.调用 getChildMeasureSpec函数获取子view的规格
* 参数一:zi view的测量规格
* 参数二:间距
* 参数三:view的高宽
*/
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);
}
}
}
先看标注1函数measureChildWithMargins:
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
//此时widthUsed =0 已经被使用的宽度空间,heightUsed =0 已经被使用的高度空间,
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
//获取子View的宽度规格
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
//获取子View的高度规格
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
//调用子View的Measure函数
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
继续查看getChildMeasureSpec函数:
/**
* @param spec 父view测量规格
* @param padding 已经被使用的空间
* @param childDimension 子View的大小
* @return
*/
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
//父view的mode
int specMode = MeasureSpec.getMode(spec);
//父view的size
int specSize = MeasureSpec.getSize(spec);
//可供View使用的剩余空间,
// 无论父view的mode是exactly或at_most或unspecified,view的大小都不可能超过size
int size = Math.max(0, specSize - padding);
// view最终可以使用的空间,但不一定就是view的最终size,如果它有子view,可能会受到子view的影响,进行调整。
int resultSize = 0;
// view的mode
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY:
//如果父Viewmode为EXACTLY,View的高宽为确定值那么其mode为exactly,resultSize 为childDimension
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
//如果父Viewmode为EXACTLY,View的高宽为MATCH_PARENT,那么其mode为exactly,resultSize 为size
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.
//如果父Viewmode为EXACTLY,View的高宽为 WRAP_CONTENT 那么其mode为 AT_MOST,resultSize 为size
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
//如果父Viewmode为 AT_MOST,View的高宽为确定值那么其mode为exactly,resultSize 为childDimension
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
//如果父Viewmode为 UNSPECIFIED,View的高宽为确定值那么其mode为exactly,resultSize 为childDimension
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);
}
说明,从函数可以看出:
(1).不管父View的mode为exactly或at_most或unspecifited,那么子View的size都不可能大于剩余空间size的大小;
(2).当子View的高宽为确定值时,那么它的mode必为exactly。
回到onMeasure函数中查看2标注的函数setMeasureDimension:
再setMeasureDimension之前先看resolveSizeAndState:
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
//view的mode
final int specMode = MeasureSpec.getMode(measureSpec);
//view的size
final int specSize = MeasureSpec.getSize(measureSpec);
final int result;
switch (specMode) {
case MeasureSpec.AT_MOST://此种情况下取最小值
if (specSize < size) {
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY://此种情况下取 specSize
result = specSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}
说明,该函数处理的结果将会作为父View的高宽进行保存。
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int opticalWidth = insets.left + insets.right;
int opticalHeight = insets.top + insets.bottom;
measuredWidth += optical ? opticalWidth : -opticalWidth;
measuredHeight += optical ? opticalHeight : -opticalHeight;
}
//调用 setMeasuredDimensionRaw 函数把高宽保存到成员变量mMeasuredWidth、mMeasuredHeight中。
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}
继续查看setMeasuerDimensionRaw函数:
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
this.mMeasuredWidth = measuredWidth;
this.mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
说明,可以看出,父view的高宽保存到了成员变量mMeasuredWidth 、mMeasuredHeight,当然我们可以通过getMeasureXXX获取其值,如下:
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
/**
* Return the full width measurement information for this view as computed
* by the most recent call to {@link #measure(int, int)}. This result is a bit mask
* as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
* This should be used during measurement and layout calculations only. Use
* {@link #getWidth()} to see how wide a view is after layout.
*
* @return The measured width of this view as a bit mask.
*/
@ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
@ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
name = "MEASURED_STATE_TOO_SMALL"),
})
public final int getMeasuredWidthAndState() {
return mMeasuredWidth;
}
/**
* Like {@link #getMeasuredHeightAndState()}, but only returns the
* raw height component (that is the result is masked by
* {@link #MEASURED_SIZE_MASK}).
*
* @return The raw measured height of this view.
*/
public final int getMeasuredHeight() {
return mMeasuredHeight & MEASURED_SIZE_MASK;
}
/**
* Return the full height measurement information for this view as computed
* by the most recent call to {@link #measure(int, int)}. This result is a bit mask
* as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
* This should be used during measurement and layout calculations only. Use
* {@link #getHeight()} to see how wide a view is after layout.
*
* @return The measured height of this view as a bit mask.
*/
@ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
@ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
name = "MEASURED_STATE_TOO_SMALL"),
})
public final int getMeasuredHeightAndState() {
return mMeasuredHeight;
}
小结:
从上述我们可以总结到,FrameLayout根据它的MeasureSpec来对每一个子View进行测量,即调用measureChildWithMargin方法,对于每一个测量完成的子View,会寻找其中最大的宽高,那么FrameLayout(wrap_content模式)的测量宽高会受到这个子View的最大宽高的影响,接着调用setMeasureDimension方法,把FrameLayout的测量宽高保存。最后则是特殊情况的处理,即当FrameLayout为wrap_content属性时,如果其子View是match_parent属性的话,则要重新设置FrameLayout的测量规格,然后重新对该部分View测量。