1、 相對佈局的基本概念
一個控件的位置它決定於它和其他控件的關係,好處:比較靈活;缺點:掌握比較複雜。
2、 相對佈局常用屬性介紹
這裏將這些屬性分成4個組,便於理解和記憶。
a)、以下4個屬性設置控件與之間的關係和位置
但是上面4個屬性並沒有設置各個控件之間是否對齊。
示例1:將控件A放置在控件B的上面,則使用android:layout_above屬性,控件佈局的效果可以有以下這麼兩種情況。
1、 控件A與控件B對齊,並且控件A是在控件B的上面。
2、 控件A沒有與控件B對齊,但是控件A又確實是在控件B的上面。
b)、以下5個屬性,設置的是控件與控件之間對齊的方式(是頂部、底部還是左、右對齊)。
示例2:在示例1的基礎上,設置控件A放置在控件B的上面,使用android:layout_above屬性,並且控件A的左邊邊緣與控件B的左邊邊緣對齊,使用android:layout_alignLeft屬性。
c)、以下4個屬性設置控件與父控件之間對齊的方式(是頂部、底部還是左、右對齊)。
d)、以下4個屬性設置控件的方向。
可以通過組合這些屬性來實現各種各樣的佈局。
注:以上屬性和其他更多屬性的作用都能在android的幫助文檔中找到;
示例3:假如要實現一個如下圖這樣佈局的程序
如果這樣的佈局要使用LinearLayout的話會比較麻煩和複雜,
1、 首先需要一個垂直佈局方向的LinearLayout,包裹所有的控件;
2、 然後在第一個LinearLayout中嵌套一個垂直方向的LinearLayout,放在上部分,在這個LinearLayout中放入一個TextView和EditText;
3、 最後還是在第一個LinearLayout中嵌套一個水平方向的LinearLayout,放在第一個LinearLayout的下部分,在這個LinearLayout中放入兩個Button,並且還得讓它們居右。
可參考下圖:
如果使用RelativeLayout會要簡單很多,下面爲main.xml的代碼。
- <?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="wrap_content"
- android:padding="10px"
- >
- <TextView
- android:id="@+id/lable"
- android:text="Type here:"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <EditText
- android:id="@+id/entry"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@android:drawable/editbox_background"
- android:layout_below="@id/lable"
- />
- <Button
- android:id="@+id/ok"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="OK"
- android:layout_below="@id/entry"
- android:layout_marginLeft="10px"
- android:layout_alignParentRight="true"
- />
- <Button
- android:id="@+id/cancel"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/ok"
- android:layout_alignTop="@id/ok"
- android:text="Cancel"
- />
- </RelativeLayout>