使用Android的XML词汇,我们可以快速地设计UI布局及包含的屏幕元素,就像web页面的HTML。每个布局文件必须包含一个根元素,根元素必须是一个View或ViewGroup对象。一旦你已经定义了根元素,你可以添加额外的layout对象或widgets作为子元素,逐步地构建一个视图层次定义你的布局。例如,下面的XML布局文件使用了纵向的LinearLayout保存一个TextView和一个Button。

<?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>

布局文件以.xml为扩展名,保存在res/layout/下面,它将会被正确地编译。我们已经定义好了布局文件,那它是怎么被加载的呢?当我们编译应用程序时,每个XML布局文件被编译成一个View资源。我们应该在应用程序代码中加载布局资源,在Activity.onCreate()回调中通过调用setContentView()实现,以R.layout.layout_file_name 形式传递给它布局资源的引用。例如,如果你的XML布局保存为main_layout.xml,你应该这样加载它:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView.(R.layout.main_layout);
}
活动中的onCreate()回调方法,当你的活动启动时被Android框架调用详细介绍了活动组件的生命周期)。