核心屬性分類
1. 相對於兄弟元件定位
| 屬性 | 效果 |
| layout_above | 底部對齊目標頂部 |
| layout_below | 頂部對齊目標底部 |
| layout_toLeftOf | 右邊對齊目標左邊 |
| layout_toRightOf | 左邊對齊目標右邊 |
| layout_alignBaseline | 基線對齊 |
| layout_alignTop/Bottom/Left/Right | 對應邊緣對齊 |
2. 相對於父容器定位
| 屬性 | 效果 |
| layout_alignParentTop/Bottom/Left/Right | 貼齊父容器對應邊緣 |
| layout_centerHorizontal | 水平置中 |
| layout_centerVertical | 垂直置中 |
| layout_centerInParent | 水平垂直皆置中 |
實戰範例 (activity_main.xml)
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dp">
<TextView android:id="@+id/label"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="標籤" android:gravity="center" />
<EditText android:id="@+id/entry"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_below="@id/label" />
<Button android:id="@+id/ok"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/entry" android:layout_alignParentRight="true"
android:text="確定" />
<Button android:id="@+id/cancel"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/entry" android:layout_toLeftOf="@id/ok"
android:text="取消" />
</RelativeLayout>
常見錯誤與技巧
- 循環依賴:A
below B,B above A 會導致渲染異常。
- ID 必須先定義(
@+id/xxx)才能被引用(@id/xxx)。
- 複雜介面建議改用
ConstraintLayout,扁平化層級、效能更好。
總結
RelativeLayout 透過相對關係實現靈活佈局,掌握上述 12 個核心屬性即可應付 90% 場景,新專案優先考慮 ConstraintLayout。