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

Android 佈局詳解:RelativeLayout 相對佈局的定位規則與梅花案例

編輯:關於 Android 開發

RelativeLayout 相對佈局入門

相對佈局是 Android 早期最常被使用的容器之一,它的核心思路是「以別人為座標」:每個子控制項都可以聲明自己相對於父容器、或相對於某個兄弟控制項的位置,而不必像線性佈局那樣排隊等候。

兩類定位屬性,兩種取值

學習 RelativeLayout 最關鍵的一件事,是把屬性分成兩組來記:

  • 以父容器為參照的屬性,例如 layout_centerInParent、layout_alignParentLeft,取值只能是 true 或 false。
  • 以兄弟控制項為參照的屬性,例如 layout_above、layout_toRightOf,取值必須是對方的 ID,寫成 @id/xxx 的形式。

換句話說,前者回答「我在父容器裡的哪個位置」,後者回答「我在誰的上/下/左/右」。搞錯這兩種取值類型,是初學者最常踩的坑。

典型案例:用五張圖片排出梅花形

下面這個例子讓一張圖片居中,其餘四張分別貼在它的上、下、左、右,形成梅花狀排列。注意每張圖片都必須先寫好 android:id,後面的兄弟節點才有辦法引用它。

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

    <ImageView
        android:id="@+id/img1"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/img2"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_above="@id/img1"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/img3"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_below="@id/img1"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/img4"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_toLeftOf="@id/img1"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/img5"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_toRightOf="@id/img1"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

實作上的兩個提醒

第一,RelativeLayout 的測量順序會依賴宣告順序,如果被參照的控制項寫在後面,需要搭配 layout_...\@+ 的宣告方式才能正確解析。

第二,相對佈局的層級很淺、效能表現不錯,適合用在「元素之間有明確相對關係」的畫面;若畫面只是單純的直向或橫向排列,線性佈局反而更直觀。

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