相对布局(RelativeLayout)

相对布局

RelativeLayout是一个用相对位置来显示子View的View组。每个View的位置可以相对与相邻元素来指定(如相对与另一个View的左边或底边),或者相对于父RelativeLayout区域位置来指定(如底部对齐,中央偏左)。

RelativeLayout是用于设计用户界面的非常强大的工具,因为它可以消除嵌套的View组,并让你的布局层次平面化,这样可以改善性能。如果你发现你使用了几个嵌套的LinearLayout组,那么你就可以使用一个单一的RelativeLayout来替代。

View定位

RelativeLayout会让子View相对与父View或相邻的View(通过ID来指定)来指定它们的位置。因此你让两个元素沿着左边框来对齐,或者是上下中央对齐,等等。默认情况,所有的子View都会被绘制在布局的左上角,因此你必须使用来自RelativeLayout.LayoutParams中的各种布局属性来定义每个View的位置。

以下是RelativeLayout中包含的有效的布局属性:

  • android:layout_alignParentTop

    如果该属性值是“true”,那么该View的上边缘要跟它的父View的上边缘来匹配。

  • android:layout_centerVertical

    如果该属性值是“true”,那么在该View父View内部,它会垂直居中。

  • android:layout_below

    该View的上边缘位于用资源ID指定的View的下面。

  • android:layout_toRightOf

    该View的左边缘位于用资源ID指定的View的右边。

这些只是一些例子,所有的布局属性在文档RelativeLayout.LayoutParams中。

每个布局属性值可能是一个相对与其父RelativeLayout的布尔值,也可能是在布局内相邻View的ID。

在你的XML布局中,可以按照任意的顺序来声明对布局中另一个View的依赖。例如,你可以声明View1位于View2的下方,即使View2在布局层次中是最后被声明的。以下示例演示了这种场景。

示例

<?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"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" >
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/reminder" />
    <Spinner
        android:id="@+id/dates"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/times" />
    <Spinner
        android:id="@id/times"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_alignParentRight="true" />
    <Button
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/times"
        android:layout_alignParentRight="true"
        android:text="@string/done" />
</RelativeLayout>

Copyright© 2020-2022 li-xyz 冀ICP备2022001112号-1