** 注:本文參考連接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只運行一次。
如上述有錯,請留言告知。