---
title: "TabActivity笔记"
author: "L.x"
date: "2012-02-16T16:04:17Z"
tags: ["Android", "Tabhost", "framelayout", "tabactivity", "tabwidget"]
categories: ["移动开发"]
slug: "tabactivity"
draft: false
lastmod: "2012-02-16T16:04:17Z"
id: 1408157
url: "https://l-x.iteye.com/blog/1408157"
---

TabActivity封装了一个TabHost组建的构建、恢复、更新过程。使客户端可以直接使用TabHost的实例，而无须关心TabHost的生命周期管理。

TabActivity.onPostCreate方法检测客户端是否自定义了TabHost。如果未定义该组件,TabActivity将设置默认的TabHost布局文件(com.android.internal.R.layout.tab\_content). 

一个TabHost\[@android:id/tabhost]主要包含了由一系列选项卡(TabSpec)构成的TabWidget\[@android:id/tabs]组建和显示当前选项卡中的内容的FrameLayout\[@android:id/tab\_content]对象. 

通过TabHost.addTab(TabSpec)方法向TabWidget组建添加选项卡及点击该选项卡显示的内容.

TabHost.setIndicator(..)、TabHost.setContent(..)大量使用了策略模式(IndicatorStrategy,ContentStrategy)、工厂模式(TabContentFactory)来构建选项卡及Tab内容视图. 

 

创建一个自定义的TabHost步骤如下:

 

1. 创建一个自定义的TabHost的layout布局文件.

```
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@android:id/tabhost" style="@style/fill_parent">
    <LinearLayout style="@style/fill_parent">
        <FrameLayout android:id="@android:id/tabcontent" style="@style/fill_parent"/>
        <TabWidget android:id="@android:id/tabs" style="@style/tabs"/>
    </LinearLayout>
</TabHost>
```

    2.  重写TabActivity中的onCreate方法,设置自定义的TabHost布局文件及创建相应的选项卡.

```
FrameLayout toFilled = getTabHost().getTabContentView();
        getLayoutInflater().inflate(tabLayoutRes, toFilled);
```