相對佈局
RelativeLayout
是一種用相對位置顯示所有子元素視圖的ViewGroup。每個視圖的位置都可以通過相對於相鄰元素的位置來指定(例如在另一個視圖的左邊或下面),或相對於在父元素 RelativeLayout 區域中的位置指定(例如底部,左邊或居中對齊)。
RelativeLayout
對於設計用戶界面來說是很強大實用的,因爲它不需要嵌套ViewGroup並且使你的佈局扁平化,這樣可以提升性能。如果你發現自己使用了很多嵌套的 LinearLayout 組,那麼你可以使用一個 RelativeLayout 替代它們。
定位視圖
RelativeLayout
可以讓子元素視圖相對於父元素視圖或其他子元素視圖的位置來指定它們的位置(通過ID指定)。所以你可以通過右邊界對齊兩個元素,或使一個在另一個下方,在屏幕居中,據中偏左等等。默認情況下,所有的子元素視圖都在佈局的左上角,所以你必須使用 RelativeLayout.LayoutParams 裏可用的各種佈局屬性定義每個視圖的位置。
在 RelativeLayout 裏包含許多視圖可用的佈局屬性中的一些:
android:layout_alignParentTop
- 若
"true"
,使視圖的頂邊與父元素的頂邊對齊。 android:layout_centerVertical
- 若
"true"
,使這個子元素在父元素中垂直居中。 android:layout_below
- 使該視圖的頂邊處於資源ID指定的視圖之下。
android:layout_toRightOf
- 使視圖的左側邊緣處於資源ID指定的視圖右側。
這只是一些事例。所有的佈局屬性在 RelativeLayout.LayoutParams 裏都有說明。
每個佈局屬性的值不是可以開啓相對於父元素 RelativeLayout 的佈局位置的布爾值,就是該視圖用來參考放置的另外的視圖的ID。
在你的XML佈局中,被依賴的視圖可以在佈局中的任何位置聲明。例如,儘管“view2”在層級中是最後一個被聲明的視圖,你仍然可以聲明“view1”在“view2”的下方。下面的實例演示了這樣的場景。
事例
控制每個視圖相對位置的屬性被加粗顯示了。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner
android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
</RelativeLayout>
請查閱 RelativeLayout.LayoutParams 瞭解更多關於 RelativeLayout 中子元素視圖所有可用佈局屬性的細節。