欢迎来到人人都可写代码,大家好,我是杨晓华,今天我们的课程内容是:Android界面布局中的相对布局。

1、RelativeLayout的概述

(1) RelativeLayout是一个允许子视图相对于其他兄弟视图或是父视图显示的视图组(通过ID指定)。每个视图的位置能够指定它相对于兄弟(比如在其他视图的左边或是下边)或是父视图(这里是指相对布局容器,比如底部对齐、中间偏左)的位置。

(2) 在相对布局中如果不指定控件摆放的位置,那么控件都会被默认放在RelativeLayout的左上角。因此要先指定第一个控件的位置,再根据一个控件去给其他控件布局。

2、RelativeLayout的属性和定位

(1) 基本属性

gravity:设置容器内组件的对齐方式。

ignoreGravity:该属性为true的组件,将不受gravity属性的影响。

margin:设置组件与父容器的边距,又叫偏移。

padding:设置组件内部元素间的边距。

(2)根据父容器定位

layout_alignParentLeft 左对齐

layout_alignParentRight 右对齐

layout_alignParentTop 顶部对齐

layout_alignParentBottom 底部对齐

layout_centerHorizontal 水平居中

layout_centerVertical 垂直居中

layout_centerInParent 中间位置

(3) 根据兄弟组件定位

layout_toLeftOf 参考组件的左边

layout_toRightOf 参考组件的右边

layout_above 参考组件的上方

layout_below 参考组件的下方

layout_alignTop 对齐参考组件的上边界

layout_alignBottom 对齐参考组件的下边界

layout_alignLeft 对齐参考组件的左边界

layout_alignRight 对齐参考组件的右边界

3、举例说明

(1)实现的布局效果:




Android 和父布局右对齐 安卓开发相对布局_android 相对布局


(2)对应的布局代码:

<?xml version="1.0" encoding="utf-8"?>
<!--【1.创建一个相对布局容器】-->
<RelativeLayout
 android:id="@+id/container"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/colorPrimaryDark"
 >
 <!--【2.创建一个居中Button layout_centerInParent= ture 】-->
 <Button
 android:id="@+id/centerBtn"
 android:layout_centerInParent="true"
 android:background="#ff0000"
 android:layout_width="100dp"
 android:layout_height="100dp" />
 <!--3.相对于中心控件的上面添加一个按钮 layout_above设置为centerBtn-->
 <Button
 android:id="@+id/topButton"
 android:layout_above="@id/centerBtn"
 android:layout_centerHorizontal="true"
 android:background="#00ffff"
 android:layout_width="100dp"
 android:layout_height="100dp" />
 <!--4.相对于中心控件的下面添加一个按钮 layout_below设置为centerBtn-->
 <Button
 android:id="@+id/buttomButton"
 android:layout_below="@id/centerBtn"
 android:layout_centerHorizontal="true"
 android:background="#00ffff"
 android:layout_width="100dp"
 android:layout_height="100dp" />
 <!--5.相对于中心控件的左面添加一个按钮 layout_toLeftOf-->
 <Button
 android:id="@+id/leftButton"
 android:layout_toLeftOf="@id/centerBtn"
 android:layout_centerVertical="true"
 android:background="#ffffff"
 android:layout_width="100dp"
 android:layout_height="100dp" />
 <!--6.相对于中心控件的左面添加一个按钮 layout_toLeftOf-->
 <Button
 android:id="@+id/rightButton"
 android:layout_toRightOf="@id/centerBtn"
 android:layout_centerVertical="true"
 android:background="#ffffff"
 android:layout_width="100dp"
 android:layout_height="100dp" />
</RelativeLayout>