这是我参与 8 月更文挑战的第 27 天,活动详情查看: 8月更文挑战
简介
RelativeLayout就是相对布局. 相对于LinearLayout的线性布局而言更具灵活性, LinearLayout仅支持水平或者垂直排列. RelativeLayout可以通过相对定位的方式让控件出现在布局的任何位置, 因此RelativeLayout的属性也非常多, 不过具有很强的规律性.本篇简单介绍RelativeLayout基于父布局的属性.
使用
相对父布局对其
注意, RelativeLayout内的所有控件默认初始位置为0.0即左上角, 如果不指定控件位置, 则所有的控件都会在左上角堆积,显示在最顶部的控件为xml布局中的最下边的控件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RelativeLayoutActivity">
<Button
android:text="左上"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="右上"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="左下"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="右下"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="居中"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="水平"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="垂直"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
基本属性
android:layout_alignParentStart 是否同父布局的开始位置对其
android:layout_alignParentLeft 是否同父布局的左边对其,其效果同android:layout_alignParentStart(推荐使用)
android:layout_alignParentEnd 是否同父布局的结束位置对其
android:layout_alignParentRight 是否同父布局的右边对其,其效果同android:layout_alignParentEnd(推荐使用)
android:layout_alignParentBottom是否同父布局的底部对其
android:layout_alignParentTop是否同父布局的顶部对其
android:layout_centerInParent指定控件是否居中父布局
android:layout_centerHorizontal指定控件是否水平居中于父布局
android:layout_centerVertical指定控件是否垂直居中于父布局