Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

layout_weight 到底怎麼分配空間?三種寫法與實測對照

編輯:Android 開發實例

layout_weight 是 LinearLayout 裡最容易被誤解也最好用的屬性。它真正的語意是「剩餘空間的分配比例」,而不是「寬度」。下面用三段配置對照說明。

情況一:寬度設為 0dip,權重 1 與 2

這是最推薦的寫法。兩個子檢視的 layout_width 都設為 0dip,讓系統完全透過權重來分配寬度,此時畫面呈現 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="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

把兩個子檢視的寬度都改成 match_parent,權重數字雖然一樣,結果卻完全不同。因為此時每個子檢視先各自佔滿整個父容器,剩下的「負空間」再依權重去扣,最終比例會與情況一明顯不同,甚至出現某個區塊被壓縮的情形。

<?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 這個標籤在 wrap_content 的情形下會佔滿全部空間,行為與一般控制項不同。這是許多人使用 Fragment 時遇到「布局跑掉」的常見原因。

實務結論

想做等比例或固定比例分割時,請一律使用「layout_width="0dip" + layout_weight」的組合。這種寫法不僅語意清楚,也能避免不必要的量測與配置,效能表現優於「先給滿寬再扣」的做法。若需要固定寬度加可伸縮區塊,則把固定那側的權重設為 0、寬度寫實際值即可。

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