Relative Layout
RelativeLayout是一個視圖組,用於顯示相對位置的子視圖。每個視圖的位置可以指定爲相對於同級元素(例如,在另一個視圖的左側或下方)或相對於父級RelativeLayout區域的位置(例如與底部,左側或中間對齊)。
RelativeLayout是一個非常強大的實用程序,用於設計用戶界面,因爲它可以消除嵌套視圖組並保持佈局層次結構平整,從而提高性能。如果您發現自己使用了多個嵌套的LinearLayout組,則可以使用單個RelativeLayout替換它們。
定位視圖
RelativeLayout允許子視圖指定它們相對於父視圖或彼此的位置(由ID指定)。因此,您可以通過右邊框對齊兩個元素,或者使另一個元素在另一個下方對齊,在屏幕中居中,向左居中,依此類推。默認情況下,所有子視圖都在佈局的左上角繪製,因此您必須使用RelativeLayout.LayoutParams中提供的各種佈局屬性來定義每個視圖的位置。
RelativeLayout中可用於視圖的一些佈局屬性包括:
如果爲“true”,則使此視圖的上邊緣與父級的上邊緣匹配。
如果爲“true”,則將此子項垂直居中於其父級。
將此視圖的上邊緣定位在使用資源ID指定的視圖下方。
將此視圖的左邊緣定位到使用資源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="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="match_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的每個子視圖可用的所有佈局屬性的詳細信息,請參閱RelativeLayout.LayoutParams。