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

Android layout_weight 怎麼用:三種情境圖解與 Fragment 特例

編輯:關於 Android 程式設計

layout_weight 是 LinearLayout 裡最實用也最容易被誤解的屬性。它的作用是:在扣除固定尺寸後,把剩餘空間依權重比例分配給子元素。搭配 layout_width="0dip" 使用時效果最穩定。

情境一:權重 1 比 2 的水平分割

左側 Fragment 佔三分之一,右側 FrameLayout 佔三分之二。關鍵在於兩個子元素的寬度都設為 0dip,讓剩餘空間成為唯一依據。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.a2bgeek.fragmentdemo.TitlesFragment" />

    <FrameLayout
        android:id="@+id/details"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="2" >
    </FrameLayout>

</LinearLayout>

情境二:寬度都寫成 match_parent,結果完全不同

同樣是 1 比 2,但只要把 layout_width 換成 match_parent,算術就變了:每個子元素先各自要求「整個父容器」,空間不足時按比例互相「退讓」,最終比例雖仍是 1:2,但在實作細節與多子元素混排時容易出現不如預期的結果。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.a2bgeek.fragmentdemo.TitlesFragment" />

    <FrameLayout
        android:id="@+id/details"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2" >
    </FrameLayout>

</LinearLayout>

情境三:Fragment 遇上 wrap_content 的陷阱

Fragment 與一般 View 不同:當它的寬高設為 wrap_content 時,並不會像 TextView 那樣依內容收縮,而是往往佔滿整個可用空間。因此在使用 Fragment 時,若非刻意要全螢幕,建議明確給 0dip + layout_weight,或直接用 match_parent 搭配權重,不要依賴 wrap_content。

使用要點整理

  • 權重是「剩餘空間」的分配比例,不是畫面的絕對比例。
  • 水平排列時搭配 layout_width="0dip";垂直排列時搭配 layout_height="0dip"。
  • 權重值可以是小數(如 0.3、0.7),不必非得是整數。
  • 權重只在同一個 LinearLayout 的同一方向上互相比較。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved