7.3 RelativeLayout布局详解

本文详细介绍了Android开发中RelativeLayout布局的使用方法,包括如何通过ID指定子元素相对于其他元素或父元素的位置,实现元素的左右对齐、上下对齐、置于屏幕中央等排列方式。文中提供了垂直方向和水平方向上的应用示例,并附上了完整代码。

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

RelativeLayout相对布局, 允许子元素指定他们相对于其它元素或父元素的位置(通过ID 指定)。因此,可以以左右对齐、上下对齐、置于屏幕中央等形式来排列元素。相对布局在实际应用中比较常用。图7-13所示是垂直方向上的应用。

[img]http://dl.iteye.com/upload/attachment/520149/0b25296b-9a5e-3747-a287-fc6454247bc1.png[/img]

图7-13 RelativeLayout1
RelativeLayout布局文件请参考代码清单7-15,完整代码请参考chapter7_3工程中relativelayout1.xml代码部分(chapter7_3/res/layout/relativelayout1.xml)。
【代码清单7-15】
<?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="wrap_content"
android:padding="10dip">
<TextView android:id="@+id/labe1" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:text="上" android:background="#ff0060" />

<TextView android:id="@+id/labe2" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentBottom="true"
android:text="下" android:background="#2121f4" />

<TextView android:id="@+id/labe3" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_above="@id/labe2"
android:layout_below="@id/labe1" android:text="中"
android:background="#ffffff" />
</RelativeLayout>

图7-14所示是水平方向上的应用。

[img]http://dl.iteye.com/upload/attachment/520151/2239f503-5844-398e-abe7-6f6ab0324f49.png[/img]

图7-14 RelativeLayout2
RelativeLayout布局文件请参考代码清单7-16,完整代码请参考chapter7_3工程中relativelayout2.xml代码部分(chapter7_3/res/layout/relativelayout2.xml)。
【代码清单7-16】
<?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="wrap_content"
android:padding="10dip">

<TextView android:id="@+id/labe4" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="@string/search" />

<EditText android:id="@+id/entry" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_below="@id/labe4"
android:background="@android:drawable/editbox_background" />

<Button android:id="@+id/ok" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/entry"
android:layout_alignParentRight="true" android:layout_marginLeft="10dip"
android:text="@string/confirm" />

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok" android:text="@string/cancel" />
</RelativeLayout>

出自《Android开发案例驱动教程》第七章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值