android 【MeasureSpec】 introduction
A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode. There are three possible modes:
- UNSPECIFIED
- The parent has not imposed any constraint on the child. It can be whatever size it wants.
- EXACTLY
- The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be.
- AT_MOST
- The child can be as large as it wants up to the specified size.
一个MeasureSpec封装了父布局传递给子布局的布局要求,每个MeasureSpec代表了一组宽度和高度的要求。一个MeasureSpec由大小和模式组成。
它有三种模式:
UNSPECIFIED(未指定),
父元素不对子元素施加任何束缚,子元素可以得到任意想要的大小;
EXACTLY(完全),
父元素决定子元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小;
AT_MOST(至多),
子元素至多达到指定大小的值。
MeasureSpecs通过实现int 来减少对象分配。此类提供了打包和解包<size,model>元组到int中。
它常用的三个函数:
1.static int getMode(int measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一)
2.static int getSize(int measureSpec):根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小)
3.static int makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)
对于此类的应用,常常写这样一个方法,在onMeasure方法里调用:
public static int resolveSize(int size, int measureSpec) { int result = size; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: result = size; break; case MeasureSpec.AT_MOST: result = Math.min(size, specSize); break; case MeasureSpec.EXACTLY: result = specSize; break; } return result; }
更多相关文章
- Android(安卓)Studio 多渠道打包(二) ---meta-data
- Android通过Movie展示Gif格式图片
- Android(安卓)实现生成二维码
- Android(安卓)UI之TextView实现图文混合效果
- Android(安卓)webview 加载H5时,隐藏掉不需要的元素
- Android之获得内存剩余大小与总大小
- android动画及用法
- 获取手机分辨率(屏幕大小)
- Android(安卓)webview上传图片(相册/相机)