一、RelativeLayout的概述
RelativeLayout(相对布局)是一种根据父容器和兄弟控件作为参照来确定控件位置的布局方式。在很多时候,线性布局还不能满足我们的需求,比如,我们在一行(列)上显示多个控件,这就需要使用RelativeLayout来进行相对布局,RelativeLayout允许子元素指定它们相对于其他元素或父元素的位置(通过ID指定)。因此,你可以以右对齐、上下或置于屏幕中央的形式来排列两个元素。元素按顺序排列,因此如果第一个元素在屏幕的中央,那么相对于这个元素的其他元素将以屏幕中央的相对位置来排列。如果使用XML来指定这个布局,在你定义它之前,被关联的元素必须定义。RelativeLayout视图显示了屏幕元素的类名称,下面是每个元素的属性列表。这些属性一部分由元素直接提供,另一部分由容器的LayoutParams成员(RelativeLayout的子类)提供。
<?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"> ...... </RelativeLayout>
二、根据父容器定位
在相对布局中,可以通过以下的属性让的组合让控件处于父容器左上角、右上角、左下角、右下角、上下左右居中,正居中等九个位置。属性如下:
android:layout_alignParentLeft="true" 父容器左边
android:layout_alignParentRight="true" 父容器右边
android:layout_alignParentTop="true" 父容器顶部
android:layout_alignParentBottom="true" 父容器底部
android:layout_centerHorizontal="true" 水平方向居中
android:layout_centerVertical="true" 垂直方向居中
android:layout_centerInParent="true" 水平垂直都居中
示例1:
<?xml version="1.0" encoding="utf-8"?>