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

Android 佈局解析:LinearLayout 的 orientation、gravity 與 weight

編輯:關於 Android 程式設計

一、LinearLayout 就像一個盒子

它把所有子元件沿同一個方向排成一列:垂直或水平。方向由 android:orientation 決定,只接受 vertical 與 horizontal 兩個值。

主要屬性

  • android:orientation:排列方向,預設為 horizontal。
  • android:gravity:決定所有子元件在容器內的對齊方式,可用 top、bottom、left、right、center、center_vertical、start、end 等,也能用 | 組合。

注意 gravity 與 layout_gravity 的差別:前者影響容器「內部所有子元件」整體的對齊,後者是子元件針對自己在容器中的對齊方式「單獨」指定。

二、寬高必填:三種取值

放在 LinearLayout 裡的元件,都必須透過 android:layout_width 與 android:layout_height 告知容器如何配置空間:

  • match_parent(舊名 fill_parent):佔滿父容器可用空間。
  • wrap_content:只佔顯示內容所需的空間。
  • 具體數值加單位。

常用單位

單位說明
px像素,螢幕上的實際點,不同 dpi 會有落差,不建議用於版面
dp(dip)密度-independent 像素。在 160dpi 螢幕上 1dp = 1px,跨裝置一致,版面首選
sp刻度-independent 像素,會隨使用者設定的字體大小縮放,文字尺寸專用
pt點,1/72 英寸
in / mm英寸 / 毫米

三、weight:按權重分配剩餘空間

android:layout_weight 決定元件「佔掉容器剩餘空間的比例」,是 LinearLayout 最實用的特性,也是其他 Layout 沒有的。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="左" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="右" />

</LinearLayout>

上例中兩個按鈕會依 1:2 分配剩餘寬度。

關鍵規則:

  • 垂直排列時使用 weight,請把 android:layout_height 設為 0dp。
  • 水平排列時使用 weight,請把 android:layout_width 設為 0dp。

為什麼?若不歸零,元件會先依內容佔掉該有的尺寸,剩下真正的「剩餘空間」才被分配,比例就不符合預期。歸零之後,容器會把整個可用空間拿來按權重切分,結果才精準。

四、其他常見佈局

  • RelativeLayout(相對佈局):以父容器或其他元件為基準定位,早期 Android 專案的預設選擇。
  • TableLayout(表格佈局):以列與行排列,可用 android:layout_columnSpan 合併欄位,元件通常包在 <TableRow> 中。
  • ScrollView:提供垂直捲動能力,但只能包含一個直接子元件,通常再包一層 LinearLayout。
  • FrameLayout:元件堆疊顯示,適合製作浮層或 Tab 內容容器。
  • ConstraintLayout:目前官方推薦,扁平化階層、效能佳,能取代大部分巢狀 LinearLayout。

實務建議

LinearLayout 適合「單純的一維排列」,超過兩層巢狀就該考慮改用 ConstraintLayout。層數越深,measure 與 layout 的計算成本越高,這在長清單或低階機上會直接反映在 FPS 上。

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