最近在看Android
開發,對於不少書上關於layout_weight
的講解感受很是費解,不少都是像公式同樣要求記住,而並未說明緣由,筆者查詢了android
的官方開發文檔,Trainning
裏面有一段關於layout_weight
屬性很是形象的描述,然後在網上看到了一篇關於這個屬性的講解,很是精彩,特此在這裏摘錄。html
layout_weight
The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.android
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.ui
這是什麼意思呢,文檔裏面說layout_weight
是用來指定視圖應當佔據的剩餘空間,這個剩餘空間是根據權重值來分配的,也就是說,若是一個視圖分配權重2,一個是1,那麼,第一個視圖將會佔據三分之二的空間,第二個視圖將會佔據三分之一的空間,默認的值是0.
可是這是在wrap_content
的狀況下,纔會發生,一旦將屬性指定爲match_parent
,那麼空間的配比就會根據權重值的反比,也就是說剛纔的狀況下第一個視圖將會佔據三分之一,而第二個視圖將會佔據三分之二。
這個特性讓人很是費解,並且不少書上都只是像背口訣同樣記住,然後筆者在網上發現了一篇文章,文章地址,裏面講述的就很清晰。spa
其實文檔裏面已經說的很清楚了,layout_weight
這個屬性是用來給剩餘空間分配的,因此咱們只須要計算剩餘空間的分配就好了,它實際上是先根據你的layout_width
或者layout_height
計算好預先的值,而後整個屏幕減去全部控件的值,計算的結果多是負數,可是沒有關係,負數同樣能夠根據比例分配,而後加總在原先的值上,這樣就成了咱們看到的畫面。rest