修改已有的自定义view尺寸
1.重写父类onMeasure()方法,调用super.onMeasure()触发继承的view的测量。
2.调用getMeasureWidth()和getMeasureHeight()取得到被继承的view的宽高
3.调用setMeasureDimension()保存你最后修改的结果
全新定义view的尺寸
1.不用再写重写onMeasure()了,父类帮不了你了
2.父view对子view的限制。
//在父view执行
@Override
rotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
child.measure();
//给子view设置了约束
child.measure(childWidthMeasureSpec,childHeightMeasureSpec);
}
//在子view执行
@Override
rotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//上面个参数就是上面两个数值的约束
int measureWidt = XXXX;
int measureHeight = XXXX;
//这里执行resolveSize()将你计算出的新尺寸和就尺寸进行修正
measureWidth = resolveSize(measureWidth, widthMeasureSpec);
measureHeight =resolveSize(measureHeight, heightMeasureSpec);
//再次保存该尺寸
setMeasureDimention(measureWidth,measureHeight)
}
3.resolveSize()方法的源码解析
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
final int specMode = MeasureSpec.getMode(measureSpec);
final int specSize = MeasureSpec.getSize(measureSpec);
final int result;
switch (specMode) {
case MeasureSpec.AT_MOST:
//如果是上限这种mode
则比较一下有没有超过上限
if (specSize < size) {
//如果没越界则用用户定义的尺寸
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
//如果越界则用原尺寸
result = size;
}
break;
case MeasureSpec.EXACTLY:
//精确限制尺寸这种mode 则直接忽略用户定义的尺寸
result = specSize;
break;
case MeasureSpec.UNSPECIFIED:
//未定义,不执行任何的操作
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}
网友评论