RelativeLayout 的每個元件都是「相對於其他元件」來定位的。常用的定位屬性有:
android:layout_below="@id/text":放在 text 的下方。android:layout_above="@id/text":放在 text 的上方。android:layout_toLeftOf="@id/text":放在 text 的左側。android:layout_alignTop="@id/text":與 text 的上緣對齊。<string name="b00">根</string> <string name="b11">莖</string> <string name="b22">花</string> <string name="b33">皮</string> <string name="b44">葉</string>
<?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">
<Button
android:id="@+id/no.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/b00" />
<Button
android:id="@+id/no.1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/no.0"
android:layout_toLeftOf="@id/no.0"
android:text="@string/b11" />
<Button
android:id="@+id/no.2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/no.0"
android:layout_toRightOf="@id/no.0"
android:text="@string/b22" />
<Button
android:id="@+id/no.3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/no.0"
android:layout_toLeftOf="@id/no.0"
android:text="@string/b33" />
<Button
android:id="@+id/no.4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/no.0"
android:layout_toRightOf="@id/no.0"
android:text="@string/b44" />
</RelativeLayout>
先在 string.xml 定義文字,再在 main.xml 用 RelativeLayout 把「根」這個按鈕以 layout_centerInParent 釘在正中央,然後以它為基準點,用 above/below 搭配 toLeftOf/toRightOf 的組合,把其餘四顆按鈕放到左上、右上、左下、右下,梅花圖案就成形了。
這個範例說明了相對布局的核心價值:先立一個錨點,其餘元件全部用「相對誰」來描述位置,不必一層層嵌套容器。