以前我們寫LinearLayout的控件的權重的時候(以水平方向來說),都會將子控件的的寬度改成0dp
,然後 android:layout_weight=”1”,來表示子控件平分剩餘空間。但是,如果子控件的寬度不設置成0dp,那個會是什麼情形呢?下面一起來看看他們的區別和算法:
- 將子控件的寬度設置成0dp
代碼如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context="com.example.linearlayout.MainActivity" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button2"
/>
</LinearLayout>
- 這個很好理解,Button1的寬度爲:1/(1 + 2 ) = 1/3。Button2的寬度爲:2/(1 + 2 ) = 2/3。但是當把這兩個個Button的寬度由0dp改成match_parent的時候,效果還會如上圖所示嗎?讓我們來做個實驗,代碼如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context="com.example.linearlayout.MainActivity" >
<Button
android:layout_width="martch_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1"
/>
<Button
android:layout_width="martch_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button2"
/>
</LinearLayout>
效果圖如下所示:
怎麼會和上圖不一樣呢???這正好是我們要講的算法,我們都知道,權重的作用是按比例分配屏幕剩餘寬度。
算法爲:控件自身的寬度 + 按比例分配的屏幕剩餘寬度
假設手機屏幕的寬度爲W,那麼每個Button的寬度也應該都是W,剩餘寬度就等於 W - (W + W) = -W。
Button1的weight=1,剩餘寬度佔比爲1/(1 + 2) = 1/3,所以,最終寬度爲 W + (1/3) * (-W) = 2/3W,Button2的計算類似,最終寬度爲W + (2/3) * (-W) = 1/3W。所以就能夠很好的理解上面兩種爲什麼會有不同的效果了。