AbsoluteLayout 又称绝对布局,放入该布局的组件需要通过 android:layout_x 和 android:layout_y 两个属性指定其准确的坐标值,并显示在屏幕上。
理论上,AbsoluteLayout 布局可用以完成任何的布局设计,灵活性很大,但是在实际的工程应用中不提倡使用这种布局。因为使用这种布局不但需要精确计算每个组件的大小,增大运算量,而且当应用程序在不同屏幕尺寸的手机上运行时会产生不同效果。
实例 AbsoluteLayoutDemo 演示了 AbsoluteLayout 布局的使用方法,效果如图 2所示。
图 1 AbsoluteLayout 布局效果
实例 AbsoluteLayoutDemo 的布局文件 main.xml 代码如下:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="32px"
android:layout_y="53px"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="146px"
android:layout_y="53px"
android:text="Button" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="85px"
android:layout_y="135px"
android:text="Button" />
</AbsoluteLayout>
其中:
android:layout_x="85px"
android:layout_y="135px"
表示将组件放置到以屏幕左上角为坐标原点的坐标系下,x 值为 85 像素、y 值为 135 像素的位置。
在这里简单介绍一下 Android 系统常用的尺寸类型的单位。
像素:缩写为 px。表示屏幕上的物理像素。
磅:points,缩写为 pt。1pt 等于 1 英寸的 1/72,常用于印刷业。
放大像素:sp。主要用于字体的显示,Android 默认使用 sp 作为字号单位。
密度独立像素:缩写为 dip 或 dp。该尺寸使用 160dp 的屏幕作为参考,然后用该屏幕映射到实际屏幕,在不同分辨率的屏幕上会有相应的缩放效果以适用于不同分辨率的屏幕。若用 px 的话,320px 占满 HVGA 的宽度,到 WVGA 上就只能占一半不到的屏幕了,那一定不是你想要的。
毫米:mm。