TabHost仅仅是一个简单的容器,它提供了newTabSpec(String tab)和addTab(TabHost.TabSapec tabSapec)两个方法,用来创建和添加选项卡。
TabHost的使用步骤:
1、在界面上定义一个TabHost组件,并为该组件定义选项卡的内容
2、Acitity里继承TabAcitity
3、调用TabActivity的getTabHost()方法获取TabHost对象
4、通过TabHost对象创建、添加选项卡
.......如果,程序里需要监控TabHost里当前标签页的改变,可以为它设置TabHost.OnTabChangeListener监听器,介绍就这么多了,其他的就看API文档了。
---------------------------------------------------------
下面是实例演示了:
继承TabActivity的例子:
main.xml的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/tabhost1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="1562622****" />
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="1562610****" />
</LinearLayout>
<LinearLayout
android:id="@+id/tabhost2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg2" />
</LinearLayout>
<LinearLayout
android:id="@+id/tabhost3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<DigitalClock
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</TabHost>
Acitity.java的关键代码如下:
public class MainActivity extends TabActivity {
private TabHost tabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
tabHost = getTabHost();
//设置使用TabHost布局
LayoutInflater.from(this).inflate(R.layout.activity_main, tabHost.getTabContentView(), true);
//添加第一个tab标签页
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("已接电话")
.setContent(R.id.tabhost1));
//添加第二个tab标签页
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("通讯录")
.setContent(R.id.tabhost2));
//添加第三个tab标签页
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("通话时间")
.setContent(R.id.tabhost3));
}
}
程序效果图: