安卓 Android RelativeLayout 相对布局

2019-02-21  本文已影响0人  已经多年不写Unity

相对布局: 假设我们需要添加五个按钮,第一个按钮相对于整个屏幕剧中,剩下四个依次排列在该布局的上下左右,如图所示,这个时候我们需要使用相对布局,更加容易实现

image

【父容器定位属性示意图】

44967125.jpg

【根据兄弟组件定位】

image

代码如下:

<?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>

实现效果如图

屏幕快照 2019-02-21 上午11.46.47.png
上一篇 下一篇

猜你喜欢

热点阅读