TabHost是一种可以方便的在窗口上放置多个标签,每个标签相当于一个容器,而在这个容器里可以放置不同的组件。
使用TabHost的一般步骤为:
1.在XML文件中定义TabHost组件,并为该组件定义该选项卡的内容;
2.创建一个类让这个类继承TabActivity;
3.调用TabActivity的getTabHost()方法获取TabHost对象;
4.通过获取的TabHost对象的方法来创建选项卡、添加选项卡。
程序:
package com.example.tabhosttset;
import android.os.Bundle;
public class TabHostTest extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost=getTabHost();
//使用tabHost布局
LayoutInflater.from(this).inflate(R.layout.activity_tab_host_test, tabHost.getTabContentView(), true);
//添加第一个标签页
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("已接电话").setContent(R.id.tab1));
//添加第二个标签
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("呼出电话", getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.tab2));
//添加第三个标签
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("未接电话").setContent(R.id.tab3));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_tab_host_test, menu);
return true;
}
}
xml:
<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
>
<!-- 定义第一个标签的内容 -->
<LinearLayout
android:id="@+id/tab1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小明 ——2012/5/15"
android:textColor="@android:color/white"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小红 ——2012/5/15"
android:textColor="@android:color/white"
/>
</LinearLayout>
<!-- 定义第二个标签 -->
<LinearLayout
android:id="@+id/tab2"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小李 ——2012/5/15"
android:textColor="@android:color/white"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小王 ——2012/5/15"
android:textColor="@android:color/white"
/>
</LinearLayout>
<!-- 定义第三个标签 -->
<LinearLayout
android:id="@+id/tab3"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小温 ——2012/5/15"
android:textColor="@android:color/white"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11dp"
android:text="小王 ——2012/5/15"
android:textColor="@android:color/white"
/>
</LinearLayout>
</TabHost>