RelativeLayout 是ViewGroup 的一種,它裡面包含的View按照相對位置進行排列,可以指定一個View跟相鄰View的位置關系(例如:在某個View的左邊,或者下面);或者指定這個View相對於RelativeLayout這個容器的位置(例如底部,或者左邊中間)。
RelativeLayout是一個很強大的工具,在設計用戶界面的時候可以消除嵌套的ViewGroup。如果你在嵌套使用LinearLayout,你應該可以用單個的RelativeLayout來取代它。
res/layout/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="fill_parent">
- <TextView
- android:id="@+id/label"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Type here:"/>
- <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/label"/>
- <Button
- android:id="@+id/ok"
- 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="OK" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/ok"
- android:layout_alignTop="@id/ok"
- android:text="Cancel" />
- </RelativeLayout>
關注每一個android:layout_* 屬性,例如layout_below, layout_alignParentRight, 還有layout_toLeftOf。 使用RelativeLayout的時候,用這些屬性來設置每個View的位置。這些屬性的每一個都定義了一種相對位置。有些屬性使用相鄰View的資源ID來定義自己的相對位置。例如,最後一個Button,被擺放在資源ID ok (這是前一個Button)的左邊,並和它上對齊。
所有的布局屬性都定義在 RelativeLayout.LayoutParams.
onCreate() 方法裝載了這個布局:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
setContentView(int) 方法裝載這個Activity的布局文件,資源ID — R.layout.main 指向res/layout/main.xml布局文件。
應該能看到下面的畫面: