measurespec和layoutparam的理解

317 阅读2分钟

1.measurespec可以理解为一种测量规格,包含测量模式mode,测量大小size。在自定义view重写onmeasure方法时,该view的父布局会将自己的measurespec传递给子view,给子view大小形成一种约束。

2.measurespec是由一个32的int整型拆分来的,高两位表示mode,低30位表示size。主要有三个方法,getmode()获取测量模式,getsize()测量大小,makemeasurespec()传入mode和size封装成一个measurespec。

3.measurespec测量模式包含三种规格,exactly确切值,unspecified未指定大小,atmost最大值。exactly表示父view为确定大小的值,或者为matchparent,子view不能超过父view的大小。 unspecified表示表示父布局不对子布局大小做限制,子布局想多大就多大。 atmost表示最大值模式,父view尺寸为wrapcontent,子view最大不能超过父布局大小。

子view的大小不仅和父布局传递给它的的measurespec有关还和它本身的layoutparam有关。

layoutparam包含了我们在xml布局文件中给它设置的layout属性,如layout-width,layout-height等。它们包含三种类型wrapcontent,matchparent和具体的值。我们可以根据父view的measurespec和子view本身的layoutparam确定子view的measurespec。具体实现在getchildmeasurespec()方法中,该方法包含三个参数,分别是父view的measurespec,父view的大小,子view的大小childdimension(如果子view的childdimension大于0,那么它有确切值)。

具体实现原理:1.父view测量模式为exactily,如果子view的childdimension>0,则子view自己有确定大小,子view的size为childdimension,子view的mode为exactily;如果子view的childdimension==matchcontent,那么子view充满父view,大小为参数传递来的父view大小,模式为exactily;如果子view的childdimension==wrapcontent,那么子view的测量模式为atmost,子view的大小为父view的size。2.父view的测量模式为atmost,如果子view的childdimension>0,那么子view的大小为childdimension,测量模式为exactily;如果子view的childdimension==matchparent,那么子view的大小为父view的size,测量模式为atmost;如果子view的childdimension==wrapcontent,那么子view的测量模式为atmost,子view大小为父view大小;3.父view的测量模式为unspecified,如果子view的childdimension>0,那么子view的测量模式为exactily,子view的大小为childdimension;如果子view的childdimension==matchparent,那么子view的测量模式为unspecified,子view的大小为0;如果子view的childdimension==wrapcontent,那么子view的大小为0,子view的测量模式为unspecified。这样最终确定了一个子view的mode和size,然后我们调用makemeasurespec方法得到子view的measurespec。