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

Android RelativeLayout 相對佈局完全指南:屬性對照與定位範例

編輯:關於 Android 程式設計

相比線性佈局與表格佈局,RelativeLayout 的彈性明顯更高,實務上出現的頻率也最高。它的核心概念只有一句話:每個控制項的位置,是相對於父容器或兄弟控制項決定的。只要先定錨一個元件,其他元件就能靠著它一路排下去。

這次要做出的畫面如下:

結構很簡單:一個 TextView 當標題、一個 EditText 讓使用者輸入、兩個 Button 並排靠右。

常用定位屬性速查

相對於其他控制項:

android:layout_above:把自己的底邊貼到指定 id 的下方元件之上。
android:layout_below:把自己的頂邊放到指定 id 的下方。
android:layout_toLeftOf:把自己的右邊緊貼在指定 id 的左側。
android:layout_toRightOf:把自己的左邊緊貼在指定 id 的右側。

相對於父容器對齊:

android:layout_alignParentRight:右邊與父容器右緣對齊。
android:layout_alignParentLeft:左邊與父容器左緣對齊。
android:layout_alignParentTop:頂端與父容器頂緣對齊。
android:layout_alignParentBottom:底端與父容器底緣對齊。

與指定控制項的邊緣對齊:

android:layout_alignBottom、android:layout_alignLeft、android:layout_alignRight、android:layout_alignTop,分別對應底部、左邊、右邊、頂端的對齊。

XML 實作

整個畫面只靠相對定位就能完成,不需要任何巢狀容器:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10px">

    <TextView
        android:id="@+id/input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/input_dis"
        tools:context=".MainActivity" />

    <EditText
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/input"
        android:background="@android:drawable/editbox_background" />

    <Button
        android:id="@+id/ok"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/edit"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10px"
        android:text="@string/ok" />

    <Button
        android:id="@+id/cancel"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/edit"
        android:layout_toLeftOf="@id/ok"
        android:text="@string/cancel" />

</RelativeLayout>

這裡有兩個值得留意的技巧。第一,EditText 用 layout_below="@id/input 接在標題下方,形成由上而下的骨架。第二,兩個按鈕都掛在 EditText 下方,但「確定」按鈕靠父容器右緣對齊,「取消」按鈕則用 layout_toLeftOf="@id/ok" 貼在確定鈕的左邊——先放好錨點,再讓其他元件靠過來,這就是相對佈局的思考順序。

另外提醒一個實務上的地雷:在 RelativeLayout 裡,被當成參照的元件必須先在 XML 中出現,否則 id 找不到,會直接導致編譯或執行期錯誤。

小結

RelativeLayout ROP 屬性雖多,但本質只有「上下左右」與「對齊誰」兩類。用得夠熟之後,很多原本需要三四層 LinearLayout 才能拼出的畫面,用一層 RelativeLayout 就能搞定,效能與可讀性都更好。

作者:tornadomeet

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