前面几期基本学习了Android开发中常用的四种布局,之所以把AbsoluteLayout放在后面来学习,是由于在实际开发中很少使用,而且在高版本中已经注释待删除不建议使用,那么本期学习的目的就是简单了解有这样一种布局,如果碰到至少知道是怎么回事。
一、认识AbsoluteLayout
绝对布局需要通过指定x、y坐标来控制每一个控件的位置,放入该布局的控件需要通过android:layout_x和android:layout_y 两个属性指定其准确的坐标值,并显示在屏幕上。
需要注意的是当使用AbsoluteLayout作为布局容器时,布局容器不再管理子组件的位置和大小,都需要开发人员自己控制。使用绝对布局时,每个子组件都可指定如下两个XML属性。
-
layout_x:指定该子组件的X坐标。
-
layout_y:指定该子组件的Y坐标。
二、示例
接下来通过一个简单的示例程序来学习AbsoluteLayout的使用用法。
同样使用WidgetSample工程,继续使用app/main/res/layout/目录下的activity_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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="0dp"
android:text="按钮1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="40dp"
android:text="按钮2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="80dp"
android:layout_y="80dp"
android:text="按钮3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="120dp"
android:layout_y="120dp"
android:text="按钮4" />
</AbsoluteLayout>
运行程序,可以看到下图所示界面效果: