首先看一個佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ff0000"
android:text="1"
android:textColor="#ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#cccccc"
android:text="2"
android:textColor="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:background="#ddaacc"
android:text="3"
android:textColor="#000000" />
</LinearLayout>
看到這個佈局,很容易想到出來的結果是什麼樣的:
然後,再來看一下改動一下的佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ff0000"
android:text="1"
android:textColor="#ffffff" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#cccccc"
android:text="2"
android:textColor="#000000" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#ff0000"
android:text="3"
android:textColor="#000000" />
</LinearLayout>
看到這裏,如果你想的還是按照: 1/5 2/5 2/5 來分的話,那就錯了。
不多說,直接看結果:
這纔是真正的結果。
總結計算方法:
1、layout_weight 這個值是,如果不指定,則默認爲0,Android系統先按照你設置的控件高度Layout_width值wrap_content,給你分配好他們3個的寬度,然後再會把剩下來的屏幕空間按權重分配給有權重的控件。
2、所以,上面這個例子。這樣算纔對:
假設屏幕寬度爲1,先按照設置的match_parent給它們設置相應的寬度先,則每人都是1,這時候算出剩餘的屏幕寬度(這裏說明一下,這個值是可以爲負值的)爲:1-3*1=-2(因爲每個都是1,所以三個,就佔用了3),剩下的屏幕寬度爲-2。然後,把這個剩下的-2按照權重分配給每個空間。例如第一個最後的寬度應該是這樣的:1+(1/5)x(-2)=3/5 第二個是:1+(2/5)x(-2)=1/5 第三個是:1+(2/5)x(-2)=1/5
3、所以,理解最重要。看不出來,就動手算一下,不用靠猜了,我也是每次都會忘記,這次應該不會了。。。。