安卓 Android RelativeLayout 相对布局
2019-02-21 本文已影响0人
已经多年不写Unity
相对布局: 假设我们需要添加五个按钮,第一个按钮相对于整个屏幕剧中,剩下四个依次排列在该布局的上下左右,如图所示,这个时候我们需要使用相对布局,更加容易实现
![](https://img.haomeiwen.com/i7693425/6473bb08b6de9257.jpg)
【父容器定位属性示意图】
![](https://img.haomeiwen.com/i7693425/50b3670a4eb64b21.jpg)
【根据兄弟组件定位】
![](https://img.haomeiwen.com/i7693425/905c46db92a2308c.jpg)
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<!--【1.创建一个相对布局容器】-->
<RelativeLayout
android:id="@+id/container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
>
<!--【2.创建一个居中Button layout_centerInParent= ture 】-->
<Button
android:id="@+id/centerBtn"
android:layout_centerInParent="true"
android:background="#ff0000"
android:layout_width="100dp"
android:layout_height="100dp" />
<!--3.相对于中心控件的上面添加一个按钮 layout_above设置为centerBtn-->
<Button
android:id="@+id/topButton"
android:layout_above="@id/centerBtn"
android:layout_centerHorizontal="true"
android:background="#00ffff"
android:layout_width="100dp"
android:layout_height="100dp" />
<!--4.相对于中心控件的下面添加一个按钮 layout_below设置为centerBtn-->
<Button
android:id="@+id/buttomButton"
android:layout_below="@id/centerBtn"
android:layout_centerHorizontal="true"
android:background="#00ffff"
android:layout_width="100dp"
android:layout_height="100dp" />
<!--5.相对于中心控件的左面添加一个按钮 layout_toLeftOf-->
<Button
android:id="@+id/leftButton"
android:layout_toLeftOf="@id/centerBtn"
android:layout_centerVertical="true"
android:background="#ffffff"
android:layout_width="100dp"
android:layout_height="100dp" />
<!--6.相对于中心控件的左面添加一个按钮 layout_toLeftOf-->
<Button
android:id="@+id/rightButton"
android:layout_toRightOf="@id/centerBtn"
android:layout_centerVertical="true"
android:background="#ffffff"
android:layout_width="100dp"
android:layout_height="100dp" />
</RelativeLayout>
实现效果如图
![](https://img.haomeiwen.com/i7693425/4b69b90aa7cc25d2.png)