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

layout_weight屬性圖解:三種典型分配場景

編輯:關於 Android 程式設計

layout_weight的作用

先按照宣告的尺寸分配,剩餘的空間再依照layout_weight進行分配。

這句話是理解layout_weight的關鍵。下面透過三個由淺入深的例子,直觀說明它的分配規則。

一、平均分配

程式碼:

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

    <TextView
        android:background="#e1d611"
        android:gravity="center"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="我是老大我是老大我是老大"
        android:textColor="#ffffff"
        android:visibility="gone" />

    <TextView
        android:background="#09c0f2"
        android:gravity="center"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="我是老二"
        android:textColor="#ffffff" />

    <TextView
        android:background="#074bc1"
        android:gravity="center"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="我是老三"
        android:textColor="#ffffff"
        android:visibility="gone" />

</LinearLayout>

此例中,三個子控制項都設定 layout_width="0dp"、layout_weight="1",因此剩餘空間會被平均分成三份。注意:使用weight時,把寬度設為0dp是較好的實務做法,能避免因內容長度不同而導致的分配不均。

二、平均且對齊

在父控制項中加入:

android:baselineAligned="false"

當子項的文字基線對齊(baselineAligned)預設為true時,可能導致各項高度略有差異、無法完全對齊。將父容器的 baselineAligned 設為false,即可讓各項在平均分配的基礎上保持整齊對齊。

三、單個分配比例

在父控制項中加入:

android:weightSum="2"

程式碼:

<LinearLayout
    android:baselineAligned="false"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:weightSum="2"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:background="#09c0f2"
        android:gravity="center"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="我是老二"
        android:textColor="#ffffff" />

</LinearLayout>

當父容器設定 weightSum="2",而唯一子項的 layout_weight="1" 時,該子項只會佔據父容器一半的寬度,另一半留白。這正是weightSum所定義的「權重總和」帶來的分配效果:子項比例 = 自身weight ÷ weightSum。

掌握這三種場景,你就能在各種排版需求中靈活、精準地運用layout_weight了。

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