之前面试的时候遇到一道问题,父View的属性(match_parent和wrap_content)对测量子view的影响,当时很蒙,没有回答上来,最近在看View源码的时候发现里面早已给出了标准答案,
先上源码
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
//父View的宽/高测量模式
int specMode = MeasureSpec.getMode(spec);
//父View的宽/高大小
int specSize = MeasureSpec.getSize(spec);
//父View剩下的可用区域
int size = Math.max(0, specSize - padding);
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
//父View_EXACTLY
case MeasureSpec.EXACTLY:
//如果子View写si了宽/高
if (childDimension >= 0) {
//子View的MeasureSpec=EXACTLY+写si的宽/高(si说多了不吉利)
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
//子View的MeasureSpec=EXACTLY+父View剩下的区域
resultSize = size