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

RelativeLayout 相對版面配置:讓每個元件對準另一個元件

編輯:Android 開發教學

使用 RelativeLayout,可以透過設定「相對位置」——也就是每個 View 相對於另一個 View 的位置——來決定子 View 的擺放。以下看 main.xml 的程式碼:

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

    <TextView
        android:id="@+id/lblComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Comments" />

    <EditText
        android:id="@+id/txtComments"
        android:layout_width="fill_parent"
        android:layout_height="170px"
        android:layout_alignLeft="@+id/lblComments"
        android:layout_below="@+id/lblComments"
        android:layout_centerHorizontal="true"
        android:textSize="18sp" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="125px"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/txtComments"
        android:layout_below="@+id/txtComments"
        android:text="Save" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="124px"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtComments"
        android:layout_below="@+id/txtComments"
        android:text="Cancel" />
</RelativeLayout>

可以觀察到,這些檢視都嵌在 RelativeLayout 裡面,每個檢視都有一些特有屬性用來對準其他檢視:

layout_alignParentTop
layout_alignParentLeft
layout_alignRight
layout_below
layout_centerHorizontal

這些屬性的值,就是被引用檢視的 id。

兩個實務要點

第一,被引用的 id 前面建議加上 @+id 而非 @id。在第一次引用時用 @+id 可以順便宣告這個 id,避免編譯時因為找不到資源而報錯。

第二,RelativeLayout 的版面配置是兩次量測(double measure),巢狀越多效能越差。因此像這種「標籤+輸入框+按鈕」的表單,雖然用 RelativeLayout 寫起來直觀,但若整個畫面由多層 RelativeLayout 堆疊而成,建議改用 ConstraintLayout,它能用扁平結構表達同樣的相對關係,效能好得多。

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