1 概述
measure方法,主要是用于测量android中view的大小,为后面的layout做好准备,这里我们主要来看measure的流程。
2 分析
查看view中的方法,
public final void measure(int widthMeasureSpec, int heightMeasureSpec)
这个方法是测量方法,但是这里这个方法是final的,也就是说无法重写,其实这里面最终是调用onMeasure来完成测量。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
android的视图测量就是从上到下遍历的测量,他的流程如下:
比较简单,值得注意的是measure方法中有一个widthMeasureSpec值,这个值是一个int,它的高两位代表了specMode,低30位代表了specsize,可以使用MeasureSpec来打包和解包这个值,从而获得mode和size。
先来看看MeasureSpec的mode:
UNSPECIFIED//不做限制
EXACTLY//指定精确值,在match_parent和具体数值时,适用与这种场景
AT_MOST//指定最大值,往往对应于layoutParams中的wrap_content
一个普通view的mode如何来确立呢,我们查看android中viewGroup的源码中的getChildMeasureSpec方法,如下:
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 =