萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android RelativeLayout 相對佈局屬性完整速查表與實戰範例

核心屬性分類

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。

copyright © 萬盛學電腦網 all rights reserved