標籤:android 線性布局 weight
之前被這個屬性困擾過好久,今天一個偶然的機會,終於把這個搞清楚了,現在與大家分享一下。
假設我們要在一個LinearLayout布局中顯示兩個按鈕,button1和button2,button2的寬度是button1的二倍,正常情況下使用weight應該是這樣的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="button1" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="button2" /></LinearLayout>
注意兩個button的寬都是0dp
:
可是如果換一種方式:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="button1" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:text="button2" /></LinearLayout>
兩個button的寬度都是match_parent,情況立馬發生轉變:
我以前就在這裡不知道糾結了多少回,那麼我們到底該怎麼理解weight這個屬性呢?
設定了weight屬性的View的寬度等於原有寬度加上剩餘空間的佔比,其中剩餘空間是指螢幕寬度相對於控制項總寬度剩餘的空間大小。
以第一種情況為例
假設螢幕寬度為L,第一個button原有寬度是0dp,那麼該button的寬度為0+(L-0)×1/3 = (1/3)L;
其中(L-0)中,L表示螢幕寬度,0表示兩個控制項的總寬度
以第二種情況為例
假設螢幕寬度為L,因為兩個都是match_parent,所以總寬度是2L,那麼對於第一個button而言,它的寬度為:L+(L-2L)×1/3 = (2/3)L
其中(L-2L)中,L表示螢幕寬度,2L表示兩個控制項的總寬度
總結:建議大家在使用weight屬性的過程中把相應的寬或者高設定為0dp,這也是Google推薦的做法。水平排列的話寬設定為0dp,豎直排列的話高設定為0dp.
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。若有錯誤地方,還望批評指正,不勝感激。
關於weight屬性使用的一些細節