layout weight 額外空間的分配

2021-07-03 11:09:41 字數 3003 閱讀 3442

這裡主要從寬度的討論layout_weight   。 layout_weight 是用來對總的額外寬度的分配的權重,把各個子view分配到的額外寬度再加上原來的寬度,就是最後的寬度大小了。

這裡關鍵在於額外寬度的計算的方法,總額外寬度是這樣計算的:父寬度 減去 各個子view的寬度之和;每個子view分配到的額外寬度 = 總額外寬度 * 權重比。

子view寬度是xml中指定的,比如 android:layout_width="0dp" ,那這個view的寬度就是0;又如android:layout_width="match_parent" ,那它的寬度就是父的寬度了;再如 android:layout_width="wrap_content" 它的實際寬度視內容而定,最大等於父的寬度;指定確定的值 android:layout_width="150dp",這樣這個view的寬度就是 150。

match_parent"

android:layout_height="200dp"

android:orientation="horizontal" >

match_parent"

android:layout_height="match_parent"

android:layout_weight="1"

android:text=""

android:background="#ff0000" />

match_parent"

android:layout_height="match_parent"

android:layout_weight="2"

android:text=""

android:background="#00ff00" />

match_parent"

android:layout_height="match_parent"

android:text=""

android:layout_weight="2"

android:background="#0000ff" />

父linearlayout寬度為match_parent , 每個textview的寬度也是match_parent, 那麼三個子textview的總寬度就是3*match_parent;這樣額外的總寬度為 match_parent - 3*

match_parent = -2*match_parent ;

第乙個 textview分配到的額外寬度為 : -2*

match_parent * 1/(1+2+2) = -2 *match_parent / 5 ; //權重是1,總權重為5

第二個 textview分配到的額外寬度為 : 

-2*match_parent * 2/(1+2+2) = -4 * match_parent / 5 ; //權重是2,總權重為5

第三個 textview分配到的額外寬度為 : 

-2*match_parent * 2/(1+2+2) = -4 * match_parent / 5 ; //權重是2,總權重為5

這樣下來 每個子textview 的原來寬度 加上 分配到的額外寬度就是最後寬度了,(注意負號)

第乙個textview的最後寬度:

match_parent + (-2 * 

match_parent 

/ 5 ) = (3/5) * match_parent  ;

第二個textview的最後寬度:

match_parent + (-4 * match_parent / 5 ) = (1/5) * match_parent  ;

第三個textview的最後寬度:

再比如:

android:layout_width="150dp

"android:layout_height="200dp"

android:orientation="horizontal" >

android:layout_width="

100dp

"android:layout_height="match_parent"

android:layout_weight="1"

android:text=""

android:background="#ff0000" />

android:layout_width="

50dp

"android:layout_height="match_parent"

android:layout_weight="2"

android:text=""

android:background="#00ff00" />

android:layout_width="

0dp"

android:layout_height="match_parent"

android:text=""

android:layout_weight="2"

android:background="#0000ff" /> 父

linearlayout寬度為150,第乙個textview 寬度100,第二個textview寬度 50,第三個textview寬度 0,那麼三個子textview總的寬度為100+50+0 = 150; 那麼額外總寬度 = 父的寬度(150) - 各個子寬度之和(150) = 0;

這樣沒有額外的總寬度來分配了,那麼最後

第乙個textview的寬度 自己的寬度(150)+額外分配到的寬度(0) = 150;

第二個textview的寬度 自己的寬度(50)+額外分配到的寬度(0) = 50;

第二個textview的寬度 自己的寬度(0)+額外分配到的寬度(0) = 0;

android 中layout weight的作用

layout weight 用於給乙個線性布局中的諸多檢視的重要度賦值。所有的檢視都有乙個layout weight值,預設為零,意思是需要顯示多大的檢視就佔據多大的螢幕空 間。若賦乙個高於零的值,則將父檢視中的可 用空間分割,分割大小具體取決於每乙個檢視layout weight 值以及該值在當前...

layout weight詳解示例

layout wlayout weight 表示該view 控制項佔據父控制項剩餘空間的比例 示例 1.未使用layout weight 第乙個 linearlayout 將父控制項全部覆蓋,無法顯示第二個。如果android layout height wrap content android l...

android中layout weight的理解

例如 xmlns android android layout width fill parent android layout height wrap content android background 00ff00 android weightsum 0 android orientation...