如果不考虑父 view 的影响,测试结果如下:
* wrap_parent -> MeasureSpec.AT_MOST
* match_parent -> MeasureSpec.EXACTLY
* 具体值 -> MeasureSpec.EXACTLY
这是一个符合我们直觉的结果。
一个 view 的 onMeasure 方法最终得到的测量规格值(测量约束值)中包含的测量模式和上面不一定对的上,这是因为 onMeasure 方法中得到的测量规格值(测量约束值)是 measure 方法传过来的,父 view 在调用 measure 方法的时候可以根据自己的情况不使用 ViewGroup 提供的 measureChildren 方法,而改变上面的映射关系,比如 RelativeLayout 中就结合其他 Layout 属性综合确定 MeasureSpec 中的模式。上面的映射关系可以直接查看 ViewGroup 类的 getChildMeasureSpec 方法,这是最简单的 measure 子 view 的方式.
ViewGroup 中 measureChild 方法如下:
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);
}
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
c