在
XML 资源文件中定义框架布局
设计程序用户界面最方便和可维护的方法是创建
XML 布局资源。这个方法极大地简化
了
UI 设计过程,将很多静态创建和用户界面控件的布局以及控件属性的定义移到 XML 中
去,取代了写代码。
XML 布局资源必须存储在/res/layout 项目目录下。让我们看看前一节介绍的框架布局。
同样地,这个屏幕基本上就是一个有三个子视图的框架布局:一个充满整个屏幕的图片,
两个文本控件绘制在它上面,每一个文本控件都是默认透明背景。这个布局资源文件命名为
/res/layout/framed.xml,在 XML 中如下定义:
1
xmlns:android="http://schemas.android.com/apk/res/android"
2
android:layout_width="fill_parent"
3
android:layout_height="fill_parent">
4
android:id="@+id/ImageView01"
5
android:layout_height="fill_parent"
6
android:layout_width="fill_parent"
7
android:src="@drawable/lake"
8
android:scaleType="matrix">
9
android:layout_width="fill_parent"
10
android:layout_height="wrap_content"
11
android:textColor="#000"
12
android:textSize="40dp"
13
android:text="@string/top_text" />
14
android:layout_width="fill_parent"
15
android:layout_height="wrap_content"
16
android:text="@string/bottom_text"
17
android:layout_gravity="bottom"
18
android:gravity="right"
19
android:textColor="#fff"
20
android:textSize="50dp" />
回忆一下,在
Activity 中,只需要在 onCreate()方法中添加一行代码来在屏幕上加载和
显示布局资源。如果布局资源存放在
/res/layout/framed.xml 文件中,这行代码应该是:
21
setContentView(R.layout.framed);
用程序定义框架布局
你 也 可 以 用 程 序 创 建 和 配 置 框 架 布 局 。 这 通 过 使 用
FrameLayout 类
(android.widget.FrameLayout)来实现。你会在 RelativeLayout.LayoutParams 类中找到具体的参
数。同样地,典型的布局参数
(android.view.ViewGroup.LayoutParams),比如 layout_height 和
layout_width,以及边距参数(ViewGroup.MarginLayoutParams),也能用在 FrameLayout 对象
上。