Android onMeasure()测量流程解析
文章目录
前言
众所周知,Android 中组件显示到屏幕上需要经历测量、布局、绘制三个阶段,我们今天来了解一下测量的流程。布局与绘制流程文章
Android onLayout()布局流程解析
Android onDraw()绘制流程解析
组件测量的那些结论
先看结论再看分析
1. )测量流程的起点是ViewRootImpl的PerformTraveals()方法 ,该方法调用performMeasure()方法,performMeasure()方法会调用根View(DecorView)的measure()方法,开启测量流程。也就是说测量流程是从根View开始的,准确来说是从根View的measure()方法开始的。因为根View是ViewGroup(FrameLayout),所以测量流程是从ViewGroup开始的。
2. )View 类有默认的onMeasure()实现,如果我们想实现自己的测量,需要重写onMeasure()方法。
根View(DecorView)是ViewGroup(FrameLayout), ViewGroup类继承自View类,View类的measure(int widthMeasureSpec, int heightMeasureSpec) 方法会调用onMeasure(widthMeasureSpec, heightMeasureSpec)方法,根据自身规则测量自己的宽高。而ViewGroup类并没有重写其父类View的onMeasure方法,Android提供给我们的系统组件(比如FrameLayout、LinearLayout等等)和我们自定义继承自View或ViewGroup的组件,一般都需要重写onMeasure()方法,如果不重写onMeasure()方法,组件是默认填满父布局的。
3. ) 对于根View(DecorView),其MeasureSpec由窗口的尺寸和其自身的LayoutParams共同决定的,对于普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同决定的。
4. ) 自定义的ViewGroup测量一般会循环自身所有的子View,调用相应的方法(measureChildWithMargins()、measureChildren方法,这两个方法都会调用getChildMeasureSpec()方法)根据自己的MeasureSpec和子View的ViewGroup.LayoutParams生成子View的MeasureSpec,并传给子View的measure(int widthMeasureSpec, int heightMeasureSpec) 方法让子View进行自身的测量。等所有的子View完成测量后,ViewGroup会根据自己的布局规则(测量规则)和子View的测量宽高完成自身的测量。
一、MeasureSpec:测量规则
想要了解测量流程我们需要先了解MeasureSpec类,MeasureSpec是View类的一个内部类。MeasureSpec的作用在于:在Measure流程中,系统会将View的LayoutParams根据父容器所施加的规则转换成对应的MeasureSpec,然后在onMeasure方法中根据这个MeasureSpec来确定View的测量宽高,view可以有自己的宽高要求,但我们要考虑MeasureSpec的规则。
我们查看MeasureSpec的源码:
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 {}
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;
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);
}
}
@UnsupportedAppUsage
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
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) {
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);
}
}
MeasureSpec是一个32位的int值,前2位是SpecMode,表示测量模式,后30位是SpecSize,表示在某种测量模式下的规格大小。MeasureSpec将SpecMode和SpecSize打包成一个int值来避免过多的对象内存分配,为了方便操作,其提供了打包的方法makeMeasureSpec,SpecMode和SpecSize也是一个int值,MeasureSpec也可以通过方法getMode和getSize得到原始的SpecMode和SpecSize。
SpecMode有三种值,如下所示。
- ) UNSPECIFIED
父容器不对View有任何限制,要多大给多大,这种情况一般用于系统内部, 我们在开发过程中基本用不到。 - )EXACTLY
父容器已经检测出View所需要的精确大小,这个时候View的最终大小就是SpecSize所指定的值。它对应于LayoutParams中的match_parent和具体的数值这两种模式。 - )AT_MOST
父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体是什么值要看不同View的具体实现。它对应于LayoutParams中的wrap_content。
二、查看测量流程源码
2.1 查看ViewRootImpl的PerformTraveals()方法
DecorView是视图的顶级View,我们添加的布局文件是它的一个子布局,而ViewRootImpl则负责渲染视图,它调用了一个performTraveals方法使得ViewTree开始三大工作流程,然后使得View展现在我们面前。该方法会依次调用:
performMeasure、performLayout、performDraw 进行测量布局绘制三大流程。
我们摘取其中一部分performMeasure代码查看:
WindowManager.LayoutParams lp = mWindowAttributes;
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
根布局的MeasureSpec是怎么来的呢?是的,就是上面的getRootMeasureSpec,查看该方法。
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
参数windowSize窗口大小,rootDimension就是根布局ViewGroup.LayoutParams,我们会使用这两个参数通过MeasureSpec.makeMeasureSpec构建一个根布局的MeasureSpec。
然后我们看到在performMeasure方法中,调用了根布局的measure(int widthMeasureSpec, int heightMeasureSpec) 方法。根布局是ViewGroup ,而ViewGroup是没有measure方法的,只有ViewGroup的父类View有measure()方法。View的measure()方法中会调用onMeasure(widthMeasureSpec, heightMeasureSpec);方法进行测量。
我们继续查看View类的默认onMeasure()方法
2.2 View类的默认onMeasure()方法
View类的默认onMeasure()方法会进行默认的测量,测量结果是通过getDefaultSize()方法获取的。
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;
}
可以看到,即使测量模式是AT_MOST,也返回了测量大小,这就是为什么我们自定义View时如果没有重写onMeasure()方法,设置自定义View是wrap_content,我们的组件会充满父布局的原因。
最后通过setMeasuredDimension方法存储我们测量的组件宽高。
根View 是FrameLayout,我们查看FrameLayout重写的onMeasure()方法。
2.3 从FrameLayout的onMeasure()方法了解自定义ViewGroup的测量行为
@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);
}
}
}
可以看到该方法先循环子View,调用ViewGroup类的measureChildWithMargins()方法,对子View进行自身测量,在所有测量的子View中找到最大宽高,然后调用resolveSizeAndState处理后用setMeasuredDimension设置为自身的宽高,最后对MATCH_PARENT布局参数的子View进行重新测量。
这里我们不详细展开,有兴趣的可以自行查看,包括其他系统的布局组件,像LinearLayout、RelativeLayout等等,测量过程都会测量子View,然后按照自身的布局特点(布局规则)进行自身的测量。
我们主要看measureChildWithMargins()方法,相同作用的还有measureChild()方法,作用都是传入ViewGroup的测量规则和子View,调用getChildMeasureSpec 生成子View的测量规则。最后将生成的子View的测量规则传入child.measure()方法方法,让子View进行自身的测量。区别在于measureChildWithMargins会考虑Margins的影响,而measureChild方法不会。
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);
}
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);
}
查看ViewGroup类的getChildMeasureSpec方法:通过父ViewGroup的测量规则和子View的布局参数,生成子View的测量规则,最后传递到子View的onMeasure()方法供自View进行自身大小的测量。
该方法展示的也就是网上流传最多的一张图片
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);
}
经过上面的查看,我们验证了开头的结论,Android组件整个测量的基本流程还是非常清晰的。