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会重写ViewonMeasure方法,父类View.onMeasure基本只是通过MeasureSpec确定大小而已,TextView等具体view会重写onMeasure方法。

5.4 ViewGroup会对包含的子View进行遍历测量,具体的子ViewMeasureSpec数据由子ViewonMeasure方法完成。

6. MeasureSpec影响因素

父容器的MeasureSpec和子ViewLayoutParams共同决定了子ViewMeasureSpec。在measure阶段View的宽和高由其measureSpec中的specSize决定

7. 扩展

clipToPadding:是否让子View裁剪以适应父Viewpadding,默认false
clipChildren:是否让子View裁剪当超过父View的边界,默认false

getLeft/getX:不要莫名其妙的将两个不同应用场景存在的方法进行对比区分,根据场景不就区分了吗。getLeft等于相对父View的距离,getX等于相对父View的左边距left+移动TranslationX

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容