随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
相对布局是指按照组件之间的相对位置来布局,如在某个组件的左边、右边、上面和下面等。下面通过梅花布局实例来演示相对布局的使用:
布局XML:
<?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" >
<!--
padding:内边距
margin:外边距
layout_toLeftOf:相对指定组件的左边放置
layout_toRightOf:相对指定组件的右边放置
layout_above:相对指定组件的上边放置
layout_below:相对指定组件的下边放置
layout_alignLeft:相对指定组件的左边对齐
layout_alignRight:相对指定组件的右边对齐
layout_alignTop:相对指定组件的上边对齐
layout_alignBottom:相对指定组件的下边对齐
以下的属性值为true或false
layout_alignParentLeft:与该组件的父组件左边对齐
layout_alignParentRight:与该组件的父组件右边对齐
layout_alignParentTop:与该组件的父组件上边对齐
layout_alignParentBottom:与该组件的父组件下边对齐
-->
<Button
android:id="@+id/btn_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="A" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/btn_a"
android:layout_toLeftOf="@id/btn_a"
android:text="C" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/btn_a"
android:layout_alignLeft="@id/btn_a"
android:text="B" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/btn_a"
android:layout_toRightOf="@id/btn_a"
android:text="D" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/btn_a"
android:layout_below="@id/btn_a"
android:text="E" />
</RelativeLayout>
附上图片效果: