measureChildWithMargins:ViewGroup中测量子控件大小的方法(measureChild方法类似)
/**
* Ask one of the children of this view to measure itself, taking into account both the MeasureSpec
* requirements for this view and its padding and margins. The child must have MarginLayoutParams The
* heavy lifting is done in getChildMeasureSpec.
* 要求子控件测量自己,考虑因素包括子控件的MeasureSpec和padding、margin,要求子控件必须有LayoutParams
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param widthUsed Extra space that has been used up by the parent horizontally (possibly by other children of
* the parent) 父控件中已经使用掉的空间
* @param parentHeightMeasureSpec The height requirements for this view
* @param heightUsed Extra space that has been used up by the parent vertically (possibly by other children of
* the parent)
*/
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
// 获取child的LayoutParams
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
// 分别获取child宽高的MeasureSpec,传入parent的MeasureSpec、parent已用空间大小,child的LayoutParams宽高
// 此处LayoutParams.MATCH_PARENT = -1,LayoutParams.WRAP_CONTENT = -2,所以指定宽高时才会得到非负数
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);
// 使用获取到的childMeasureSpec为参数调用子控件的measure方法
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
getChildMeasureSpec:获取child的MeasureSpec
/**
* Does the hard part of measureChildren: figuring out the MeasureSpec to pass to a particular child.
* This method figures out the right MeasureSpec for one dimension (height or width) of one child view.
* The goal is to combine information from our MeasureSpec with the LayoutParams of the child to get the best
* possible results. For example, if the this view knows its size (because its MeasureSpec has a mode of
* EXACTLY), and the child has indicated in its LayoutParams that it wants to be the same size as the parent,
* the parent should ask the child to layout given an exact size.
* 该方法用于计算要传递给子控件的MeasureSpec,一次计算一个子控件一个方向上的MeasureSpec,目标就是根据父控件的MeasureSpec
* 以及子控件的LayoutParams算出最好的可能结果
* @param spec The requirements for this view 父控件自身的MeasureSpec
* @param padding The padding of this view for the current dimension and margins, if applicable 父控件的
* padding和margin
* @param childDimension How big the child wants to be in the current dimension 子控件要求的大小
* @return a MeasureSpec integer for the child
*/
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
case MeasureSpec.EXACTLY: // 1.父控件本身受到精确测量的要求
if (childDimension >= 0) {
// 1.1子控件要求的大小为一个精确值,则子控件的MeasureSpec就是精确测量到指定大小
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
// 1.2子控件要求是充满父控件,而父控件剩余大小是确定的,所以子控件的MeasureSpec就是精确测量到父控件剩余大小
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.
// 1.3子控件要求自定义大小,所以子控件的MeasureSpec就是最大限制到父控件剩余大小
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST: // 2.父控件本身受到最大限制,大小不确定
if (childDimension >= 0) { // 2.1子控件要求的大小为一个精确值,则子控件的MeasureSpec就是精确测量到指定大小
// 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.
// 2.2子控件要求与父控件同大小,父控件大小不确定,则子控件的MeasureSpec就是最大限制到父控件剩余大小
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.
// 2.3子控件要求自定义大小,则子控件的MeasureSpec就是最大限制到父控件剩余大小
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED:// 3.父控件本身未指定大小,大小不确定
if (childDimension >= 0) {// 3.1子控件要求的大小为一个精确值,则子控件的MeasureSpec就是精确测量到指定大小
// 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
// 3.2子控件要求与父控件同大小,父控件大小不确定,则子控件的MeasureSpec就是未指定,根据flag决定返回0或父剩余大小
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
// 3.3子控件要求自定义大小,则子控件的MeasureSpec就是未指定,根据flag决定返回0或父控件剩余大小
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
//noinspection ResourceType // 合成MeasureSpec
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
总结一下获取子控件MeasureSpec的情况有几种:
1. 当子控件的LayoutParams为指定值时,不管父控件的测量模式和剩余空间大小,返回的MeasureSpec就是指定值精确测量
2. 当子控件的LayoutParams为MATCH_PARENT时,子控件的测量模式跟随父控件的测量模式,size等于父控件的剩余空间
3. 当子控件的LayoutParams为WRAP_CONTENT时,子控件的基本模式就是不超过父控件大小
Measure方法
/**
* This is called to find out how big a view should be. The parent
* supplies constraint information in the width and height parameters. 实际测量工作在onMeasure方法中完成
* The actual measurement work of a view is performed in {@link #onMeasure(int, int)}, called by this method.
* Therefore, only {@link #onMeasure(int, int)} can and must be overridden by subclasses.
* @param widthMeasureSpec Horizontal space requirements as imposed by the parent 父控件要求的水平空间
* @param heightMeasureSpec Vertical space requirements as imposed by the parent 父控件要求的垂直空间
* @see #onMeasure(int, int)
*/
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);
final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
// Optimize layout by avoiding an extra EXACTLY pass when the view is
// already measured as the correct size. In API 23 and below, this
// extra pass is required to make LinearLayout re-distribute weight.
final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
|| heightMeasureSpec != mOldHeightMeasureSpec;
final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
&& MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
&& getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
final boolean needsLayout = specChanged
&& (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
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) {
// 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
}
onMeasure方法
/**
* Measure the view and its content to determine the measured width and the measured height. This method is
* invoked by {@link #measure(int, int)} and should be overridden by subclasses to provide accurate and
* efficient measurement of their contents.
* <strong>CONTRACT:</strong> When overriding this method, you <em>must</em> call {@link
* #setMeasuredDimension(int, int)} to store the measured width and height of this view. Failure to do so will
* trigger an <code>IllegalStateException</code>, thrown by {@link #measure(int, int)}. Calling the superclass'
* {@link #onMeasure(int, int)} is a valid use.
* The base class implementation of measure defaults to the background size, unless a larger size is allowed by
* the MeasureSpec. Subclasses should override {@link #onMeasure(int, int)} to provide better measurements of
* their content.
* If this method is overridden, it is the subclass's responsibility to make sure the measured height and width
* are at least the view's minimum height and width ({@link #getSuggestedMinimumHeight()} and
* {@link #getSuggestedMinimumWidth()}).
* @param widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded
* with {@link android.view.View.MeasureSpec}.
* @param heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded
* with {@link android.view.View.MeasureSpec}.
* @see #getMeasuredWidth()
* @see #getMeasuredHeight()
* @see #setMeasuredDimension(int, int)
* @see #getSuggestedMinimumHeight()
* @see #getSuggestedMinimumWidth()
* @see android.view.View.MeasureSpec#getMode(int)
* @see android.view.View.MeasureSpec#getSize(int)
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
getDefaultSize
/**
* Utility to return a default size. Uses the supplied size if the MeasureSpec imposed no constraints. Will
* get larger if allowed by the MeasureSpec.
*
* @param size Default size for this view // view的默认大小,view的最小宽度或者背景的最小宽度两者最大值
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
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;
}
getSuggestedMinHeight
/**
* Returns the suggested minimum width that the view should use. This returns the maximum of the view's
* minimum width and the background's minimum width
* ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
* When being used in {@link #onMeasure(int, int)}, the caller should still ensure the returned width is
* within the requirements of the parent.
*
* @return The suggested minimum width of the view.
*/ // 获取建议最小宽度,View的最小宽度可以由xml属性指定或者调用setMinimumWidth指定
protected int getSuggestedMinimumWidth() { // 如果没有背景则返回最小宽度,有背景则返回最小宽度和背景最小值两者最大值
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
/** // 设置view的最小宽度,但是不保证view可以达到这个最小宽度,如果父布局限制到更小的宽度
* Sets the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum
* width (for example, if its parent layout constrains it with less available width).
* @param minWidth The minimum width the view will try to be.
* @see #getMinimumWidth()
* @attr ref android.R.styleable#View_minWidth
*/
public void setMinimumWidth(int minWidth) {
mMinWidth = minWidth;
requestLayout();
}
setMeasuredDimension:
/**
* <p>This method must be called by {@link #onMeasure(int, int)} to store the measured width and measured
* height. Failing to do so will trigger an exception at measurement time.</p>
* @param measuredWidth The measured width of this view. May be a complex
* bit mask as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
* @param measuredHeight The measured height of this view. May be a complex
* bit mask as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
*/
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(measuredWidth, measuredHeight);
}
/**
* Sets the measured dimension without extra processing for things like optical bounds.
* Useful for reapplying consistent values that have already been cooked with adjustments
* for optical bounds, etc. such as those from the measurement cache.
*
* @param measuredWidth The measured width of this view. May be a complex
* bit mask as defined by {@link #MEASURED_SIZE_MASK} and
* {@link #MEASURED_STATE_TOO_SMALL}.
* @param measuredHeight The measured height of this view. May be a complex
* bit mask as defined by {@link #MEASURED_SIZE_MASK} and
* {@link #MEASURED_STATE_TOO_SMALL}.
*/
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}