Android布局---相对布局(Relative Layout)

本文详细介绍了Android开发中的RelativeLayout,这是一种能够简化布局设计并提升性能的视图组。RelativeLayout允许开发者通过相对定位方式来设置子视图的位置,包括相对于父视图及相邻视图的位置。文中提供了具体的XML布局示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文译自:http://developer.android.com/guide/topics/ui/layout/relative.html

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="fill_parent"

    android:layout_height="fill_parent"

    android:paddingLeft="16dp"

    android:paddingRight="16dp" >

    <EditText

        android:id="@+id/name"

        android:layout_width="fill_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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值