简介
MeasureSpec封装了父元素对子元素的布局要求。MeasureSpec对象代表了对宽或者高的布局要求,它由大小(size)和模式(mode)组成,有如下三种模式:
- UNSPECIFIED:父元素对子元素尺寸没有限制,子元素能获得想要的任何大小;
- EXACTLY:父元素决定子元素的尺寸,不管子元素的实际尺寸;
- AT_MOST:父元素决定子元素的尺寸上限。
方法
- public static int getMode (int measureSpec):获取指定MeasureSpec的模式;
- public static int getSize (int measureSpec):获取指定MeasureSpec的尺寸;
- public static int makeMeasureSpec (int size, int mode):根据尺寸和模式创建MeasureSpec实例;
使用
MeasureSpec通常在ViewGroup中用到,可以根据MeasureSpec里面的参数调节子元素的大小。下面看看它在ListView.measureItem(View child)中的使用:
private void measureItem(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
mListPadding.left + mListPadding.right, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}