當我們使用linearlayout線性布局,放置三個textview空間,設置android:layout_width屬性為wrap_content,並分別設置android:layout_weight比重為1,2,3時:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:layout_width="fill_parent"
3 android:layout_height="fill_parent" >
4
5 <TextView
6 android:id="@+id/textView1"
7 android:layout_width="wrap_content"
8 android:layout_height="wrap_content"
9 android:layout_weight="1"
10 android:background="#990033"
11 android:text="1" />
12
13 <TextView
14 android:id="@+id/textView2"
15 android:layout_width="wrap_content"
16 android:layout_height="wrap_content"
17 android:layout_weight="2"
18 android:background="#339933"
19 android:text="2" />
20
21 <TextView
22 android:id="@+id/textView3"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_weight="3"
26 android:background="#0000CC"
27 android:text="3" />
28
29 </LinearLayout>
可以看到三個textview所占的寬度比為1:2:3,似乎時根據我們所設置的android:layout_width比重實現了比例控制,然而,當我們試着把textview1的文本內容修改為111111111時
原有的比例平衡被打破了,現在三個textview的寬度比不再是1:2:3。為什么呢?因為layout_width屬性並不對整個可用空間進行分配,而是對剩余空間進行分配,也就是說系統會先按layout_width設置的屬性先給控件分配空間,在這里的代碼里是先分配空間使得每個控件足以包裹住內容,再將剩余的內容按layout_weight所設置的比例進行分配,控件最終的空間大小是layout_width屬性設置的空間大小加上按比例分得的剩余空間大小,你細心觀察將可以發現,上圖UI中除去內容之外的控件還是1:2:3。
這時候我們layout_width的屬性改為0dp試試:
這時出現了兩行 可使用 android:maxLine="1"
我們再來看一個更好玩的,將layout_width設置為match_parent屬性,再將三個控件比例設置為1:2:2:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:layout_width="fill_parent"
3 android:layout_height="fill_parent" >
4
5 <TextView
6 android:id="@+id/textView1"
7 android:layout_width="match_parent"
8 android:layout_height="wrap_content"
9 android:layout_weight="1"
10 android:background="#990033"
11 android:text="1" />
12
13 <TextView
14 android:id="@+id/textView2"
15 android:layout_width="match_parent"
16 android:layout_height="wrap_content"
17 android:layout_weight="2"
18 android:background="#339933"
19 android:text="2" />
20
21 <TextView
22 android:id="@+id/textView3"
23 android:layout_width="match_parent"
24 android:layout_height="wrap_content"
25 android:layout_weight="2"
26 android:background="#0000CC"
27 android:text="2" />
28
29 </LinearLayout>
不是說好按比例控制的嗎?為什么textview1所占的比例為1,確比占比為2的控件獲得的空間更大的呢?
我們來用剛剛的公式好好算算:
剩余空間,是用父控件的大小也就是1個parent減去layout_width所設置的屬性大小,每個控件原本的大小都設置為match_parent,也就是每個控件原本就應該獲得1個parent控件的大小,這里有3個textview控件,也就是剩余空間的大小=1個parent-3個parent大小=-2個parent,於是textview1的大小=原來的大小1個parent+分配的剩余空間大小就是(-2parent)*1/5,最后等於3/5個parent,而其余的兩個控件可以算出是1/5個parent,所以比例是3:1:1。