當我們使用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>
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiETPwJWZ3ZCMwcTP39zZuBnLENTJENTJ3pVdC5GT1EleOJTQU5UNrpWT0lEVNFTTE50dRRUT4lFRNRTQq5EeBpWT0NGVNdXRE1EN4M0T3lFVNdXS6x0MFRUT4FERPZ3YyI2cKJDT0ljMZVXTzold41WW15UbMFTRE1UeNhlWuZ0ViBXO5xkNNh0YwIFSh9CXt92YuM3YltWas5iclN3Ztl2Lc9CX6MHc0RHaiojIsJye.png)
可以看到三個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。