Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

徹底搞懂 Android layout_weight 的分配規則

編輯:關於 Android 程式設計

layout_weight 是使用 LinearLayout 時幾乎必備的屬性,但它的行為有個反直覺之處,讓不少人第一次用時都栽了跟頭。搞懂背後的計算方式,之後排版會順手很多。

它到底是什麼

子元件可以透過 layout_weight 設定自己在 LinearLayout 中的「重要度」,也就是佔用的空間比重。若不設定,預設值為 0,代表不參與多餘空間的分配。而官方文件說「weight 值越低則元件越重要」,這句話正是最容易誤解的地方——真正決定誰佔得多,還要看你把 layout_width 設成了什麼。

實驗一:width 設為 fill_parent

放兩個 Button,Button1 的 weight 為 1、Button2 為 2,兩者的 layout_width 都設為 fill_parent:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button1" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button2" />

</LinearLayout>

結果是 Button1 佔了螢幕寬度的三分之二,Button2 佔三分之一。

實驗二:width 改為 wrap_content

把兩者的 layout_width 都改成 wrap_content,其餘不動:

這次結果剛好相反:Button1 佔三分之一,Button2 佔三分之二。

為什麼會顛倒

關鍵在於 LinearLayout 分配剩餘空間的方式。它的計算大致是:先依 layout_width/layout_height 配置元件的「初始尺寸」,算出剩餘空間,再依 weight 比例去分配這塊剩餘空間。

當 width 是 fill_parent 時,兩個 Button 每個都先要佔滿整個寬度,總需求量是螢幕的兩倍,因此剩餘空間是負值(等於「超標」了一個螢幕寬)。這時 weight 的作用變成「誰該被壓縮多少」:weight 大的被壓得比較多,所以 weight 為 2 的 Button2 反而比較窄。

當 width 是 wrap_content 時,每個 Button 只先佔用自己文字所需的寬度,剩餘空間是正的。這時 weight 就是真正的「瓜分額度」:weight 為 2 的 Button2 分到兩倍的額度,自然比較寬。

所以「weight 越低越重要」這句話,嚴格說來只在 width 為 fill_parent 的情境下成立,此時 weight 是「被犧牲的程度」,數字越小損失越少。而在 wrap_content 情境下,weight 才是直覺意義上的「佔比」。

實戰技巧:固定一個、吃掉剩下

常見需求是:左側元件依內容決定寬度,右側元件吃掉所有剩餘空間。做法如下:

  • 左側:layout_width="wrap_content",不設 weight。
  • 右側:layout_width="0dp",layout_weight="1"。

這裡最容易被忽略的細節是右側要寫 0dp 而不是 fill_parent/match_parent。用 0dp 表示「我不預先索取任何空間,全部靠 weight 分配」,可以避免先配置再分配的兩段式計算,不僅行為更可預期,也省下一輪不必要的量測,效能更好。這是在複雜版面中調整整體效能時,值得優先檢查的一處。

另外提醒,layout_weight 只在 LinearLayout 中有效。若在 FrameLayout 上看到它被寫上去(網路上不少範例如此),那個屬性其實是被忽略的,真正生效的是 layout_gravity。理解這一點,看別人的版面檔時就不會被誤導。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved