相對佈局是指按照組件之間的相對位置來進行佈局,如某個組件在另外一個組件的左邊、右邊、上方、下方。其基本語法格式以下:android
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 屬性列表> </RelativeLayout>
RelativeLayout支持的經常使用XML屬性以下:佈局
XML屬性 | 描述 |
android:gravity | 用於設置佈局管理器中各子組件的對齊方式 |
android:ignoreGravity | 用於執行某個組件不受gravity屬性的影響 |
在相對佈局管理器中,只有上面介紹的兩個屬性是不夠的,爲了更好的控制該佈局管理器中各子組件的佈局分佈,RelativeLayout提供了一個內部類RelativeLayout.LayoutParams,經過該類提供的大量XML,能夠很好的控制相對佈局管理器中各組件的分佈方式,RelativeLayout.LayoutParams支持的XML屬性以下:spa
XML屬性 | 描述 |
android:layout_above | 其屬性值爲其餘UI組件的id屬性,用於指定該組件位於那個組件的上方 |
android:layout_below | 其屬性值爲其餘UI組件的id屬性,用於指定該組件位於那個組件的下方 |
android:layout_toLeftOf | 其屬性值爲其餘UI組件的id屬性,用於指定該組件位於那個組件的左方 |
android:layout_toRightOf | 其屬性值爲其餘UI組件的id屬性,用於指定該組件位於那個組件的右方 |
android:layout_alignTop | 其屬性值爲其餘UI組件的id屬性,用於指定該組件與哪一個組件的上邊界對齊 |
android:layout_alignBottom | 其屬性值爲其餘UI組件的id屬性,用於指定該組件與哪一個組件的下邊界對齊 |
android:layout_alignLeft | 其屬性值爲其餘UI組件的id屬性,用於指定該組件與哪一個組件的左邊界對齊 |
android:layout_alignRight | 其屬性值爲其餘UI組件的id屬性,用於指定該組件與哪一個組件的右邊界對齊 |
android:layout_alignParentTop | 屬性爲boolean值,用於指定該組件是否與佈局管理器頂端對齊 |
android:layout_alignParentBottom | 屬性爲boolean值,用於指定該組件是否與佈局管理器底端對齊 |
android:layout_alignParentLeft | 屬性爲boolean值,用於指定該組件是否與佈局管理器左邊對齊 |
android:layout_alignParentRight | 屬性爲boolean值,用於指定該組件是否與佈局管理器右邊對齊 |
android:layout_ | 屬性爲boolean值,用於指定該組件是否位於佈局管理器水平居中的位置 |
android:layout_ | 屬性爲boolean值,用於指定該組件是否位於佈局管理器垂直居中的位置 |
android:layout_ | 屬性爲boolean值,用於指定該組件是否位於佈局管理器的中央位置 |
<?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:gravity="center"> <TextView android:id="@+id/relativetext1" android:textSize="48px" android:text="發現又新版本,您是否如今就安裝嗎?" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/relativebutton1" android:text="如今更新" android:layout_below="@id/relativetext1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/relativebutton2" android:text="之後再說" android:layout_below="@+id/relativetext1" android:layout_toRightOf="@id/relativebutton1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
樣例效果以下:code