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

Android 版面按比例佈局的實作程式碼

編輯:關於 Android 程式設計

想讓子 View 依比例分配寬度或高度,可以善用 LinearLayout 的權重(weight)機制。做法是把 LinearLayout 的寬度或高度設為 fill_parent,再將子 View 的寬度或高度設為 0,最後為每個子 View 指定不同的權重,它們的大小就會依權值成比例。

本例採用橫向 LinearLayout,並將 android:layout_width 設為 match_parent 以使用整個螢幕寬度。對於幾個子 View,把它們的寬度都設為 0dip,再用 layout_weight 指定比例。本例中四個 TextView 使用了相同的權值,因此它們會擁有相同的寬度;而顯示文字較長的 TextView 則會自動換行增高。

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

    <TextView
        android:background="@drawable/red"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_small"/>

    <TextView
        android:background="@drawable/green"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_big"/>

    <TextView
        android:background="@drawable/blue"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_small" />

    <TextView
        android:background="@drawable/yellow"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_wrap"/>

</LinearLayout>

關鍵觀念:只要把可撐開的那個維度設為 0dip 再搭配 layout_weight,就能讓版面依權重精準地按比例切分,這是實作等寬欄位或多欄比例配置最直覺的方式。

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