文章目录
- 介绍
- 常见属性
- 根据父容器定位
- 根据兄弟组件定位
 
- 通用属性
- margin 设置组件与父容器的边距
- padding 设置组件内部元素的边距
 
- 项目结构
- 主要代码
介绍
RelativeLayout是一个相对布局,如果不指定对齐位置,都是默认相对于父容器的左上角的开始布局
常见属性
根据父容器定位
- layout_alignParentLeft:左对齐
- layout_alignParentRight:右对齐
- layout_alignParentTop:顶部对齐
- layout_alignParentBottom:底部对齐
- layout_centerHorizontal:水平居中
- layout_centerVertical:垂直居中
- layout_centerInParent:中间位置
根据兄弟组件定位
- layout_toLeftOf:放置于参考组件的左边
- layout_toRightOf:放置于参考组件的右边
- layout_above:放置于参考组件的上方
- layout_below:放置于参考组件的下方
- layout_alignTop:对齐参考组件的上边界
- layout_alignBottom:对齐参考组件的下边界
- layout_alignLeft:对齐参考组件的左边界
- layout_alignRight:对齐参考组件的右边界
通用属性
margin 设置组件与父容器的边距
- layout_margin:上下左右偏移
- layout_marginLeft:左偏移
- layout_marginRight:右偏移
- layout_marginTop:上偏移
- layout_marginBottom:下偏移
padding 设置组件内部元素的边距
项目结构

主要代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:padding="50dp"android:layout_height="match_parent"><RelativeLayoutandroid:id="@+id/rl1"android:layout_width="100dp"android:layout_height="100dp"android:layout_centerInParent="true"android:background="#ff0000" /><!--    这里发现如果不进行任何设置的话会将上面的布局进行一个覆盖--><RelativeLayoutandroid:layout_width="100dp"android:layout_height="100dp"android:layout_toRightOf="@+id/rl1"android:background="#00ff00" /><RelativeLayoutandroid:layout_alignParentBottom="true"android:layout_marginLeft="100dp"android:layout_width="100dp"android:layout_height="100dp"android:background="#0000ff" /></RelativeLayout>