首先看一個布局:
<?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>
看到這個布局,很容易想到出來的結(jié)果是什么樣的:
這里寫圖片描述
然后,再來看一下改動一下的布局:
<?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 來分的話,那就錯了。
不多說,直接看結(jié)果:
這里寫圖片描述
這才是真正的結(jié)果。
總結(jié)計算方法:
1、layout_weight 這個值是,如果不指定,則默認(rèn)為0,Android系統(tǒng)先按照你設(shè)置的控件高度Layout_width值wrap_content,給你分配好他們3個的寬度,然后再會把剩下來的屏幕空間按權(quán)重分配給有權(quán)重的控件。
2、所以,上面這個例子。這樣算才對:
假設(shè)屏幕寬度為1,先按照設(shè)置的match_parent給它們設(shè)置相應(yīng)的寬度先,則每人都是1,這時候算出剩余的屏幕寬度(這里說明一下,這個值是可以為負(fù)值的)為:1-3*1=-2(因為每個都是1,所以三個,就占用了3),剩下的屏幕寬度為-2。然后,把這個剩下的-2按照權(quán)重分配給每個空間。例如第一個最后的寬度應(yīng)該是這樣的:1+(1/5)x(-2)=3/5 第二個是:1+(2/5)x(-2)=1/5 第三個是:1+(2/5)x(-2)=1/5
3、所以,理解最重要。看不出來,就動手算一下,不用靠猜了,我也是每次都會忘記,這次應(yīng)該不會了。。。。