定义并展现你的视图层次的最常用的方法是使用XML 布局文件。
如同HTML 一样,XML 为布局提供了一种可读的结构。XML 中的每个元素都是View 或ViewGroup 对象(抑或它们的子类)。
View 对象是树的叶节点,而ViewGroup 对象是树的分支。
XML 元素的名称与它体现的Java 类相对应。所以一个元素将在你的UI 中生成一个TextView,而则创建一个LinearLayout 视图组。
当你载入一个布局资源时,Android 系统会根据你布局中的元素初始化这些运行时对象。
举例来说,一个包含文本视图和一个按钮的简单垂直布局如下:<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
请注意:LinearLayout 元素包含了TextView 和Button 对象。
你可以在其中另外安置一个LinearLayout (或其它类型的视图组),以延展这个视图层次,构建更复杂的布局。
提示:您也可以用Java 代码来绘制View 和ViewGroup 对象,并用addView(View)方法动态的插入新的View 和ViewGroup 对象。
您有相当多的方法来对视图进行布局。使用大量不同种类的视图组,您可以有近乎无穷的方式来构建子视图和视图组。Android 提供了一些预定义的视图组,其中包括LinearLayout, RelativeLayout,AbsoluteLayout, TableLayout, GridLayout 以及其它的一些。每个都为定义子视图和布局结构提供了一套独特的布局参数。