Android SDK 定义了多种布局方式以方便用户设计 UI。各种布局方式均为 ViewGroup 类的子类,结构如图 1 所示。
图 1 Android SDK 布局方式结构图
FrameLayout 又称单帧布局,是 Android 所提供的布局方式里最简单的布局方式,它指定屏幕上的一块空白区域,在该区域填充一个单一对象。例如图片、文字、按钮等。
应用程序开发人员不能为 FrameLayout 中填充的组件指定具体填充位置,默认情况下,这些组件都将被固定在屏幕的左上角,后放入的组件会放在前一个组件上进行覆盖填充,形成部分遮挡或全部遮挡。
开发人员可以通过组件的 android:layout_gravity 属性对组件位置进行适当的修改。
实例 FrameLayoutDemo 演示了 FrameLayout 的布局效果。该布局中共有 4 个 TextView 组件,前 3 个组件以默认方式放置到布局中,第 4 个组件修改 gravity 属性后放置到布局中,运行效果如图 2 所示。
图 2 FrameLayout 的布局效果
实例 FrameLayoutDemo 中的布局文件 main.xml 的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00ff00"
android:textsize="1OOdip"
android:text="@string/first"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00ffff"
android:textsize="70dip"
android:text="@string/second"/>
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffOOOO"
android:textsize="40dip"
android:text="@string/third"/>
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fffffOO"
android:textSize="40dip"
android:layout_gravity="bottom"
android:text="@string/forth"/>
</FrameLayout>
其中:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
表明 FrameLayout 布局覆盖了整个屏幕空间。
实例 FrameLayoutDemo 中的 strings.xml 文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<resources>
<string name="app_name">FrameLayoutDemo</string>
<string name="first">第一层</string>
<string name="second">第二层</string>
<string name="third">第三层</string>
<string name="forth">第四层</string>
</resources>
从运行后的结果可见,前 3 个被放置到 FrameLayout 的 TextView 组件都是以屏幕左上角为基点进行叠加的。第4个 TextView 因为设置了 android:layout_gravity="bottom" 属性而显示到了布局的下方。可自行将 android:layout_gravity 属性值修改为其他属性,查看运行效果。