1. 程式人生 > >Android官方文件—User Interface(Layouts)(Relative Layout)

Android官方文件—User Interface(Layouts)(Relative Layout)

Relative Layout

RelativeLayout是一個檢視組,用於顯示相對位置的子檢視。每個檢視的位置可以指定為相對於同級元素(例如,在另一個檢視的左側或下方)或相對於父級RelativeLayout區域的位置(例如與底部,左側或中間對齊)。

RelativeLayout是一個非常強大的實用程式,用於設計使用者介面,因為它可以消除巢狀檢視組並保持佈局層次結構平整,從而提高效能。如果您發現自己使用了多個巢狀的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="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。