onMeasure中的MeasureSpec测量规则
1. MeasureSpec.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.
2. MeasureSpec.AT_MOST
The child can be as large as it wants up to the specified size.
3. MeasureSpec.UNSPECIFIED
The parent has not imposed any constraint on the child. It can be whatever size it wants.
4. MeasureSpec
创建规则
规则图
5. 调用关系
5.1 ViewGroup
调用:onMeasure
-> forEachChild
(measureChildWithMargins
-> getChildMeasureSpec
-> View
.measure
-> View
.onMeasure
)
5.2 View
调用:onMeasure
-> setMeasuredDimension
-> getDefaultSize
-> getSuggestedMinimunWidth
/getSuggestedMinimunHeight
-> determinMeasureWidthorHeight
5.3 ViewGroup
会重写View
的onMeasure
方法,父类View
.onMeasure
基本只是通过MeasureSpec
确定大小而已,TextView
等具体view
会重写onMeasure
方法。
5.4 ViewGroup
会对包含的子View
进行遍历测量,具体的子View
的MeasureSpec
数据由子View
的onMeasure
方法完成。
6. MeasureSpec
影响因素
父容器的MeasureSpec
和子View
的LayoutParams
共同决定了子View
的MeasureSpec
。在measure
阶段View
的宽和高由其measureSpec
中的specSize
决定
7. 扩展
clipToPadding
:是否让子View
裁剪以适应父View
的padding
,默认false
clipChildren
:是否让子View
裁剪当超过父View
的边界,默认false
getLeft
/getX
:不要莫名其妙的将两个不同应用场景存在的方法进行对比区分,根据场景不就区分了吗。getLeft
等于相对父View
的距离,getX
等于相对父View
的左边距left
+移动TranslationX
。