(五)View的测量 MeasureSpec类

来源:互联网 发布:ubuntu 16.04改中文 编辑:程序博客网 时间:2024/05/17 23:00
MeasureSpec类
      MeasureSpec是一个32位的int值,高两位为SpecMode(测量模式),低30位为SpecSize(测量大小)。
      SpecMode(测量模式)分类:
      EXACTLY模式:父容器已经测出了View所需要的精确大小,此时View的最终大小就是SpecSize所指定的值。对应math_parent具体数值两种模式。
     AT_MOST模式: 父容器指定一个可用大小即SpecSize,View的大小不能超出此值,具体根据不同View的具体实现不同。一般对应wrap_content.
     UNSPECTFIED模式:父容器不对View进行限制,一般用于系统内部。

     系统内部通过MeasureSpec来进行View测量的,正常情况下使用View指定MeasureSpec,尽管如此,我们可以给View设置LayoutParams。在测量时,系统将LayoutParams在父容器的约束下转化成对应MeasureSpec,然后根据MeasureSpec确定高和宽。:LayoutParams和父容器一起才能决定View的MeasureSpec。
     顶级View(DecorView)的MeasureSpec由窗口尺寸和其自身的LayoutParams来共同决定。它的创建过程在源码中表现为:在ViewRootImpl的measureHierarchy方法中调用了getRootMeasureSpec(int 屏幕尺寸,int LayoutParams),该方法返回具体的measurespec,传入math_parent具体数值,返回EXACTLY,传入wrap_content返回AT_MOST。之后将返回的值传入performMeasure(int,int)方法。
     对于普通View来说,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同决定,View的measure的过程由ViewGroup传递过来,在ViewGroup的measureChildWithMargins方法中调用getChildMeasureSpec方法返回Child高和宽的MeasureSpec,之后调用child.measure方法。getChildMeasureSpec方法的具体实现逻辑如

下图:



原创粉丝点击