1. 相对布局含义
相对布局分两种,一种是相对于当前控件的父视图布局,例如在父视图的中间,左下角之类的。
还有一种是相对于指定视图布局,在指定布局的右边,上边之类的。
2. 相对父视图布局
直接看实例即可:
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAllCaps="false"
android:text="centerInParent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textAllCaps="false"
android:text="centerHorizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textAllCaps="false"
android:text="centerVertical" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:textAllCaps="false"
android:text="alignParentLeft" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textAllCaps="false"
android:text="alignParentRight" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="alignParentBottom" />
</RelativeLayout>
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yN4QDZ3QmYmJWMjJTZ0UmYmVGO0gzN5IzY2gjY5YTY48CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
3. 相对指定视图布局
我们先定义一个视图元素,然后其他元素均相对于该元素布局。
<?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">
<Button
android:id="@+id/btnHere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAllCaps="false"
android:text="centerInParent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btnHere"
android:textAllCaps="false"
android:text="layout_above" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnHere"
android:textAllCaps="false"
android:text="layout_below" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnHere"
android:textAllCaps="false"
android:text="alignLeft" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnHere"
android:textAllCaps="false"
android:text="alignTop" />
</RelativeLayout>