** 注:本文参考连接How Android caculates view sizeandroid
本文例子以下所示:ide
<LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:layout_width="match_parent" android:layout_height="20dp" /> </LinearLayout>
计算view大小的过程能够分为如下几个步骤:post
LayoutParams用于view表示想要的size的模式。有如下三种:字体
MeasureSpec表示当前view的“约束”(在onMeasure中传入)。约束含模式mode和数值size,当前view根据mode来决定如何看待其中的size。.net
mode有三种,以下所示:code
能够利用MeasureSpec的getMode取出具体值.ci
size为8个byte的int值,mode放在前2个bit中。这里能够利用MeasureSpec的getSize取出size的具体值。get
view经过onMeasure肯定本身的大小。肯定本身的大小时,须要的东西有:it
最终肯定当前view的size分别为:io
之前面例子中的TextView为例,其onMeasure中传入的MeasureSpec为:
注:这里先不解释为何MeasureSpec是这样的。
TextView的LayoutParams为:
而后TextView根据约束和LayoutParams肯定本身的大小,包括但不限于如下过程:
之前面例子中的LinearLayout为例,假设该LinearLayout为Activity中的root layout其onMeasure中传入的MeasureSpec为:
RelativeLayout的LayoutParams为:
而后LinearLayout根据约束和LayoutParams肯定本身的大小,包括但不限于如下过程:
要肯定child view的size,就要调用child view的onMeasure,传入合适的MeasureSpec,代表parent view对child的约束。
根据parent view的不一样module和child view的不一样LayoutParams,有以下规则:
当parent view的mode是EXACTLY时:
child layout | mode | size | |
---|---|---|---|
exact size | EXACTLY | childSize | Child wants a specific size. |
MATCH_PARENT | EXACTLY | parentContentSize | Child wants to be parent's size. |
WRAP_CONTENT | AT_MOST | parentContentSize | Child wants to determine its own size. It can not be bigger than parent. |
当parent view的mode是AT_MOST时:
child layout | mode | size | |
---|---|---|---|
exact size | EXACTLY | childSize | Child wants a specific size |
MATCH_PARENT | AT_MOST | parentContentSize | Child wants to be parent's size, but parent's size is not fixed. Constrain child to not be bigger than parent. |
WRAP_CONTENT | AT_MOST | parentContentSize | Child wants to determine its own size, but it can not be bigger than parent. |
当parent view的mode是UNSPECIFIED时:
child layout | mode | size | |
---|---|---|---|
exact size | EXACTLY | childSize | Child wants a specific size. |
MATCH_PARENT | UNSPECIFIED | can not decide yet | Child wants to be parent's size. Child will decide its own size later. |
WRAP_CONTENT | UNSPECIFIED | can not decide yet | Child wants to be its own size. Child will decide its own size later. |
以例子中的TextView为例:
因此TextView的onMeasure会被传入:
TextView能够根据上述约束计算本身的大小。ImageView同理。最后LinearLayout根据ImageView和TextView的大小计算本身的大小。注意这里没有weight的设置,因此onMeasure只运行一次。
如上述有错,请留言告知。