分析理解View的源码——Measure
自定义控件,我们只会去写几个生命周期的方法,写个自定义属性,这些只是表层,最近闲来无事,去看看android的源码,下面是看后的一些体会。
view创建需要执行Measure、Layout、Draw。先来看下Measure的执行。
在自定义View类中,会有这两个参数widthMeasureSpec、heightMeasureSpec。父View是以什么方式来控制子View呢。
MeasureSpec:
1.测量规范中是父view对子view的测量要求,每一个MeasureSpec只包含一种规范,要不然是父view对子view的宽度测量要求,要不然是高度测量要求。测量规范是一个int类型的数值,测量规范由Mode和Size两部分构成,具体来说,一个今天数值的前两位代表Mode的值,后30位代表Size的值;
2.测量规范的Mode有三种
1.UNSPECIFIED(未做限制)父view,没有对子view做限制(一般使用不到,平时使用也就是在listview)
2.EXACTLY(明确大小)父View明确了子view的大小
3.AT_MOST(最多不超过父类)没有明确大小,但是不能超过父类。
MeasureSpec.getMode(widthMeasureSpec); 可以得到Mode
MeasureSpec.getSize(widthMeasureSpec); 可以得到父类制定的Size,这个Size可以自己去重新测量,再通过MeasureSpec.makeMeasureSpec(resultSize, resultMode) 获得一个新的MeasureSpec值。
3.makeMeasureSpec方法介绍。
public static int makeMeasureSpec(int size, int mode) {
if (sUseBrokenMakeMeasureSpec) {//判断是否是17版本或者更低的版本
return size + mode;
} else {//
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
sUseBrokenMakeMeasureSpec = tagSDKVersion <= JELLY_BEAN_MR1 (判断版本是否是17版本,或者更低版本)
在SDK17之前,MeasureSpec的值是size和mode的两个值的和,但是相加可能会造成溢出值,溢出值会影响获取到MeasureSpec的值,这是一个bug,在17之后谷歌做了修改,所以开发最好适配17以上的版本。
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
获取Mode和Size都是通过MeasureSpec参数,通过与MODE_MASK这个值来判断。
11左移30位,再去进行 & 运算,这样可以的到32位数中的前两位数值,前两位数值代表Mode。在对其取反,进行&运算,就可以得到32位数中的后30位,后30位代表的是size的大小。
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);
}
此方法是在执行measure的时候换判断view是否是光影效果,例如阴影,光晕等效果,如果有的的需要多得到的MeasureSpec的值进行调整。
OnMeasure:
1.介绍,用来测量view及其内容的宽和高,会得到一组measureWidth和measureHeight的值,接下来会调用measure方法(view中的public方法),View的子类应该复写onMeasure方法,提供一组精确有效的测量值。
2.注意,重写onMeasure方法,一定要调用setMeasureDimension()方法来储存测量得到的宽高值,如果没有调用后面会抛出illegalStateException()异常,调用父类的onMeasure()方法,也可以避免抛出此异常。
3.如果在测量中没有规定更大的值,那么基类中测量值默认是backgroud的大小,建议view的子类重写onMeasure方法来进行更好的测量。
4.onMeasure方法介绍:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
onMeasure的代码很少,只是调用了setmeasureDimension()方法,但是传入的参数,是经过计算后得到的值。
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
该方法返回的是所建议的view应该使用的最小宽度--在view的最小宽度和背景的最小宽度中取最大的返回值。
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中带的mode和size属性,来得到size的具体值。
如果Mode是UNSPECIFIED,则size是getSuggestedMinimunWidth()的返回值,即view的默认最小宽度或者背景的最小宽度之一。
如果Mode是AT_MOST、EXACTLY,则size是measureSpec中带的size。
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
boolean optical = isLayoutModeOptical(this); //判断此控件是否有特殊光学(阴影、光晕)的边界(android5.0添加的判断)
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);
}
此方法是用来保存View所测量的宽和高,在调用重写onMeasure的时候要调用此方法,否则会触发异常。
public static boolean isLayoutModeOptical(Object o) {
return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
}
boolean isLayoutModeOptical() {
return mLayoutMode == LAYOUT_MODE_OPTICAL_BOUNDS;
}
用来判断布局的属性是否包含光学边界属性,有两种情况我们测量的measuredWidth会受到这个影响
一种是父View有特殊边界,子View没有。 optical 为false ,子view的布局参数应该减去父View对应的光学边界
一种是父View没有特殊边界,子View有。 optical 为true ,子view的布局参数应该加上其对应的光学边界
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
保存所测量的宽和高的值,并且设置标志位flag,用来判断有没有调用此方法。
measure:
当onMeasure方法执行结束后就会执行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);
}
// 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
}
measure做了什么呢? 主要是对measureWidth和measureHeight做了一个缓存的map,其中key是两个数据拼接的64位二进制数。
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;
}
sIgnoreMeasureCache = targetSdkVersion < KITKAT;
public static final int KITKAT = 19;
measure方法进行了一个判断,到底是需要从缓存区独处还是调用onMeasure方法重新测量,对于此判断还有一个版本的界限,如果是19版本一下的,无论有没有缓存,都会强制调用onMeasure,19版本以上不会。
// 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()");
}
如果没有调用onMeasure方法,就需要调用setMeasureDimensionRaw方法来存储width和height。
如果调用了就会根据flag来判断是否调用了setMeasureDimension方法,如果没有调,会抛出异常。
如果集成ViewGroup在调用measure之前需要测量每一个child。
viewGroup默认帮我们实现了三个通用测量child的方法:
但是每一种布局,都有自己的独特属性,例如LinearLayout、RelativeLayout两种布局的onMeasure方法实现都不同,所以ViewGroup没有重写onMeasure方法,而是让每一个子类去实现,在里面之封装三个通用的方法,方便自定义。
measureChildren() 测量每一个child
mesureChild() 测量一个child
measureChildWithMargins(); 带margin测量child
会调用MeasureChildren方法测量每一个子view。
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
1.Child的MeasureSpec怎么得到的。
2.Child的MeasureSpec的值和父ViewGroup有没有关系。
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
通过此方法,使用参数冲的padding和parent的MeasureSpec参数,得到每一个child的MeasureSpec,在通过measure得到具体的width和height。
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:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
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.
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
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
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);
}
得到child的mode和size之后,通过makeMeasureSpec方法,得到child的MeasureSpec,有9种情况,大家可以根据代码和图片分析一下,剩下的跟View走的Measure方法一样。
刚才看的方法是measureChild方法,除此之外还有一种常见的操作measureChildWithMargins方法,两种方法都去调用getChildMeasureSpec方法,那有什么区别呢?
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);
}
1.measureChildWithMargins()和measureChild()都是用来测量子view的大小;
2.两者在调用getChildMeasureSpec()都要计算父View已占的空间。
3.measureChild()计算父View所占空间为mPaddingLeft + mPaddingRight,即父容器左右两侧的padding值之和。
4.measureChildWithMargins()计算父View所占空间为mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin + widthUsed。此处,除了父容器左右两侧的padding值之和还包括了子view左右的margin值之和(lp.leftMargin + lp.rightMargin),因为这两部分也是不能用来摆放子View的,应该算父容器已经占用的空间。
终于算看完了measure的过程。
measureChildWithMargins