相对布局中的一个视图的定位是相对于它的兄弟元素的,(如它左边或下边的元素),或者是相对于RelativeLayout域的(如对齐底部,左边或者中部)
RelativeLayout是一个设计用户界面时强有力的功能,因为它可以代替嵌套的ViewGroup。如果 你发现自己使用了好几个嵌套的LinearLayout,你可以用一个简单的RelativeLayout来代替.
1.新建一个名为 HelloRelativeLayout的工程
2.打开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,你可以使用这些属性来定位每一个视图元素。这些属性中的每一个的值都指定了一个不同的相对位置。 有些属性使用 一个兄弟视图的资源 id号来进行自我定位。如,最后 一个button通过ID号为ok的元素,定位到OK的左边,并且顶部与OK对齐。
所有可用的布局属性在 RelativeLayout.LayoutParams. 中定义。
3.确信你在onCreate方法中下载了这个布局。
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);} 4.运行,效果如下。