MeasureSpec 测量规格
什么是 MeasureSpec?
Section titled “什么是 MeasureSpec?”View 的 MeasureSpec 由 父容器的 MeasureSpec 和 自身的 LayoutParams 共同决定;对于顶级 View(DecorView),则由窗口尺寸和自身 LayoutParams 共同决定。
MeasureSpec 本质上是一个 32 位 int 值:
- 高 2 位:
SpecMode(测量模式) - 低 30 位:
SpecSize(规格尺寸)
三种测量模式(SpecMode)
Section titled “三种测量模式(SpecMode)”| 模式 | 说明 | 对应典型布局参数 |
|---|---|---|
UNSPECIFIED |
无限制,父容器不对子 View 施加尺寸约束 | 系统内部测量、滚动容器(如 ScrollView) |
EXACTLY |
精确模式,最终尺寸就是 SpecSize |
match_parent 或固定 dp 数值 |
AT_MOST |
最大模式,尺寸不能超过 SpecSize |
wrap_content |
核心源码方法
Section titled “核心源码方法”ViewGroup.getChildMeasureSpec(int spec, int padding, int childDimension):描述了父容器的MeasureSpec与子 View 的LayoutParams尺寸如何共同计算出子 View 的MeasureSpec。View.getDefaultSize(int size, int measureSpec):描述了系统默认如何根据MeasureSpec解析出最终测量尺寸。