weight代表權重,也就意味着使用layout_weight會根據控件設定的權重配置設定大小,它的計算公式為:
# 實際尺寸: 子控件最終展示出來的尺寸
# 目前尺寸: 子控件剛被放到布局中, 系統還沒有解析其weight屬性時的尺寸
# weight比例: 子控件在所有有`layout_weight`屬性的控件中所占的比例
# (例: 三個子控件, 第一個比重為1, 第二個為2, 第三個為2,
# 那麼第一個所占比例為1/5, 第二個為2/5, 第三個為2/5)
# 剩餘空間: 子控件剛被放到父控件中, 系統還沒有解析其weight屬性時父控件還有多少剩餘空間
剩餘空間 = 父控件尺寸 - 子控件1尺寸 - 子控件2尺寸 - 子控件3尺寸...
實際尺寸 = 目前尺寸 + weight比例 * 剩餘空間尺寸
layout_weight
屬性很容易預測最終效果, 它們會按照自己的
weight比例
去配置設定
剩餘空間尺寸,注意是剩餘控件尺寸。
先看一個例子:
<?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:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/begin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
</LinearLayout>
布局很簡單,一個LinearLayout中包含了兩個按鈕,寬度都為wrap_content,layout_weight一個是1,一個是2,效果如下:

這個很容易了解,button1權重是1, button2權重是2,假設螢幕寬度為W,那麼:
button1的寬度就是: 1/(1+2)*W,即為螢幕寬度的1/3;
button2的寬度就是: 2/(1+2)*W,即為螢幕寬度的2/3;
那button本身的寬度有什麼作用呢?我們把兩個按鈕的寬度都設定為match_parent時,看看運作效果:
結果居然反過來了!button1占據了螢幕寬度的2/3,button2占據了1/3!!!這是為什麼呢?
額外控件尺寸!
button1和button2都設定了match_parent,兩個控件需要的尺寸為2*W,那麼剩餘空間尺寸為W-2*W=-W,由此:
button1的weight為1,那麼它的實際尺寸為: W+ 1/(1+2)*-W= 2/3*W;
button2的weight為2,那麼它的實際尺寸為: W+ 2/(1+2)*-W= 1/3*W;
是以才會出現上面的結果。要了解layout_weight配置設定的是額外空間尺寸,而不是螢幕尺寸!!
再加一個控件button3,使得它們的layout_weight為1:2:3:
<?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:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/begin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="Button3" />
</LinearLayout>
此時觀察運作效果,會發現button3雖然占據的權重最大,但它居然都沒有在螢幕上顯示:
這是為什麼呢,我們可以按照上面的計算方式,再計算下每個控件的實際尺寸:
button1、button2、button3都設定了match_parent,三個控件需要的尺寸為3*W,那麼剩餘空間尺寸為W-3*W=-2*W,由此:
button1的weight為1,那麼它的實際尺寸為: W+ 1/(1+2+3)*-2*W= 2/3*W;
button2的weight為2,那麼它的實際尺寸為: W+ 2/(1+2+3)-2*W= 1/3*W;
button3的weight為3,那麼它的實際尺寸為: W+ 3/(1+2+3)-2*W= 0;
button3的實際大小為0,當然不顯示啦~~
接着修改,把button1的寬度設定為match_parent,button2的寬度設定為wrap_content,此時的效果為:
按理說,button1設定了match_parent,它應該占滿整個螢幕寬度,這樣button2就不應該顯示,可實際上button2卻顯示出來了,這是為什麼呢?我一直沒想明白,查了下,網上說wrap_content是包裹内容的最小尺寸,而layout_weight設定的是盡可能的顯示,并不是不顯示,wrap_cotent是有一個最小值的,但是這個最小值是怎麼計算的呢?看了下View的onMeasure()方法,也并沒有發現有預設值/最小值一說,費解啊。。。。
哪位大佬幫我解釋下.....