一、相对布局(RelativeLayout)概述

相对布局(RelativeLayout)是一种根据父容器和兄弟控件作为参照来确定控件位置的布局方式。
在这里插入图片描述

使用相对布局,需要将布局节点改成RelativeLayout,基本格式如下:

 
<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=".MainActivity">
 ....
    
</RelativeLayout>

二、根据父容器定位

在相对布局中,可以通过以下的属性让的组合让控件处于父容器左上角、右上角、左下角、右下角、上下左右居中,正居中等九个位置。属性如下:

  • android:layout_alignParentLeft="true" 父容器左边
  • android:layout_alignParentRight="true" 父容器右边
  • android:layout_alignParentTop="true" 父容器顶部
  • android:layout_alignParentBottom="true" 父容器底部
  • android:layout_centerHorizontal="true" 水平方向居中
  • android:layout_centerVertical="true" 垂直方向居中
  • android:layout_centerInParent="true" 水平垂直都居中
    在这里插入图片描述
    举例:给一个控件添加 android:layout_alignParentRight="true" 和- android:layout_alignParentTop="true" 属性后该控件处于父容器右上角在这里插入图片描述

给一个控件添加 android:layout_alignParentLeft="true"android:layout_centerVertical="true" 属性后该控件处于父容器左边垂直居中位置
在这里插入图片描述

三、根据兄弟控件定位

在相对布局中,还支持通过已确定位置的控件作为参考来确定其他控件的位置,以下的属性让的组合让控件处于另外控件左上角、右上角、左下角、右下角、正上方、正下方、正左方、正右方等位置。属性如下:

  • android:layout_toLeftOf="@+id/button1" 在button1控件左方

  • android:layout_toRightOf="@+id/button1" 在button1控件右方

  • android:layout_above="@+id/button1" 在button1控件上方

  • android:layout_below="@+id/button1" 在button1控件下方

  • android:layout_alignLeft="@+id/button1" 与button1控件左边平齐

  • android:layout_alignRight="@+id/button1" 与button1控件右边平齐

  • android:layout_alignTop="@+id/button1" 与button1控件上边平齐

  • android:layout_alignBottom="@+id/button1" 与button1控件下边平齐
    在这里插入图片描述

给一个控件添加 android:layout_toLeftOf="@+id/button1"android:layout_below="@+id/button1" 属性后该控件处于button1的左下方位置
在这里插入图片描述

给一个控件添加 android:layout_toLeftOf="@+id/button1"layout_alignTop="@+id/button1" 属性后该控件处于button1的正左方
在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐