Relative Layout 相對佈局
RelativeLayout是透過指定其內部子元件間相對位置或者是父容器的相對位置,達到控制元件位置的目的。
在相對佈局的情況下,如果沒設定子元件的位置,預設會將其放在「左上角」。因此如果有二個子元件皆沒設定的話,就會有重疊的情況產生。
當在設計相對佈局時,第一件事就是需先確定第一個元件的位置及設置ID,之後的元件可以依此元件進行相對位置的編排。
當參考的元件位置改變了,依附在此元件的所有元件,皆會依此調動,不需做額外的調整。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:text="Center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/label"
android:layout_centerHorizontal="true"
android:text="TOP" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/label"
android:layout_centerHorizontal="true"
android:text="Bottom" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/label"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Bottom" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/label"
android:layout_centerVertical="true"
android:text="Bottom" />
</RelativeLayout>
相對位置參數
根據父容器定位
layout_centerInParent
在父容器的正中間
layout_centerHorizontal
水平置中
layout_centerVertical
垂直置中
layout_alighParentLeft
左對齊
layout_alighParentRight
右對齊
layout_alighParentTop
頂部對齊
layout_alighParentBottom
底部對齊
根據兄弟元件定位
layout_toRightOf
指定元件的右邊
layout_toLeftOf
指定元件的左邊
layout_below
指定元件的下方
layout_above
指定元件的上方
layout_alignTop
對齊參考元件的上邊界
layout_alignBottom
對齊參考元件的下邊界
layout_alignLeft
對齊參考元件的左邊界
layout_alignRight
對齊參考元件的右邊界