常见属性
根据父容器定位
layout_alignParentStart
左对齐
layout_alignParentEnd
右对齐
layout_alignParentTop
顶部对齐
layout_alignParentBottom
底部对齐
layout_centerHorizontal
水平居中
layout_centerVertical
垂直居中
layout_centerInParent
中间位置
根据兄弟容器定位
layout_toStartOf
放置于参考组件的左边
layout_toEndOf
放置于参考组件的右边
layout_above
放置于参考组件的上边
layout_below
放置于参考组件的下边
layout_alignLeft
对齐参考组件左边界
layout_alignRight
对齐参考组件右边界
layout_alignTop
对齐参考组件上边界
layout_alignBottom
对齐参考组件下边界
实例
<?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:background="@color/purple_200"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:background="@color/purple_500"
android:layout_width="100dp"
android:layout_height="100dp"/>
</RelativeLayout>
在xml里实现上面的代码以后,可以发现,由于RelativeLayout是相对位置,默认位置都在父容器左上角,所以我们声明的两个子容器是重叠的。
根据父容器定位
<RelativeLayout
android:layout_centerInParent="true"
android:background="@color/purple_200"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:layout_centerInParent="true"
android:background="@color/purple_200"
android:layout_width="100dp"
android:layout_height="100dp"/>
根据兄弟组件定位
<RelativeLayout
android:background="@color/purple_500"
android:layout_toStartOf="@+id/layout1"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:background="@color/purple_500"
android:layout_above="@+id/layout1"
android:layout_width="100dp"
android:layout_height="100dp"/>
通用属性
设置组件与父容器的边距
layout_margin
上下左右边距
layout_marginStart
layout_marginEnd
layout_marginTop
layout_marginBottom
设置父容器与组件的边距
padding
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/layout1"
android:layout_centerInParent="true"
android:background="@color/purple_200"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:background="@color/purple_500"
android:layout_width="100dp"
android:layout_height="100dp"/>
</RelativeLayout>