android設置組件所佔的比例

當咱們使用linearlayout線性佈局,放置三個textview空間,設置android:layout_width屬性爲wrap_content,並分別設置android:layout_weight比重爲1,2,3時:android

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。code

  這時候咱們layout_width的屬性改成0dp試試:
xml

這時出現了兩行 可以使用 android:maxLine="1"blog

咱們再來看一個更好玩的,將layout_width設置爲match_parent屬性,再將三個控件比例設置爲1:2:2:class

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的控件得到的空間更大的呢?im

  咱們來用剛剛的公式好好算算:d3

  剩餘空間,是用父控件的大小也就是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。layout