7.3 RelativeLayout布局詳解
RelativeLayout相對布局, 允許子元素指定他們相對於其它元素或父元素的位置(通過ID 指定)。因此,可以以左右對齊、上下對齊、置於屏幕中央等形式來排列元素。相對布局在實際應用中比較常用。圖7-13所示是垂直方向上的應用。
圖7-13 RelativeLayout1
RelativeLayout布局文件請參考代碼清單7-15,完整代碼請參考chapter7_3工程中relativelayout1.xml代碼部分(chapter7_3/res/layout/relativelayout1.xml)。
【代碼清單7-15】
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:andro
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dip">
<TextView android: android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:text="上" android:background="#ff0060" />
<TextView android: android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentBottom="true"
android:text="下" android:background="#2121f4" />
<TextView android: android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_above="@id/labe2"
android:layout_below="@id/labe1" android:text="中"
android:background="#ffffff" />
</RelativeLayout>
圖7-14所示是水平方向上的應用。

圖7-14 RelativeLayout2
RelativeLayout布局文件請參考代碼清單7-16,完整代碼請參考chapter7_3工程中relativelayout2.xml代碼部分(chapter7_3/res/layout/relativelayout2.xml)。
【代碼清單7-16】
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:andro
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dip">
<TextView android: android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="@string/search" />
<EditText android: android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_below="@id/labe4"
android:background="@android:drawable/editbox_background" />
<Button android: android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/entry"
android:layout_alignParentRight="true" android:layout_marginLeft="10dip"
android:text="@string/confirm" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok" android:text="@string/cancel" />
</RelativeLayout>
出自《Android開發案例驅動教程》第七章
最後更新:2017-04-02 06:51:45