下面以一个十分简洁的例子介绍一下TabHost的使用:
首先创建一个布局文件:(注意标注绿色部分)
<?xml version="1.0" encoding="utf-8"?>
<TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TabWidget>
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout
android:id="@+id/view1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/phone1"/>
</FrameLayout>
<TextView android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is another tab"/>
<TextView android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is third tab"/>
</FrameLayout>
</LinearLayout>
</TabHost>
Activity代码:注意标红部分,如果我们的Activity不是继承TabActivity的话,就不会有getTabHost()方法
public class Chapter6TabHostActivity extends TabActivity {
//声明TabHost对象
private TabHost tabhost;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取TabHost对象
tabhost=getTabHost();
/*
* 为TabHost添加标签
* 新建一个标签newTabSpec
* 设置其标签和图标
* 设置内容
*/
tabhost.addTab(tabhost.newTabSpec("1")
.setIndicator("Tab1",getResources().getDrawable(android.R.drawable.alert_dark_frame))
.setContent(R.id.view1));
tabhost.addTab(tabhost.newTabSpec("2")
.setIndicator("Tab2",getResources().getDrawable(android.R.drawable.alert_light_frame))
.setContent(R.id.textview2));
tabhost.addTab(tabhost.newTabSpec("3")
.setIndicator("Tab3",getResources().getDrawable(android.R.drawable.arrow_down_float))
.setContent(R.id.textview3));
tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
if(tabId.equals("1")){
Toast.makeText(Chapter6TabHostActivity.this, "你选择:"+tabId, Toast.LENGTH_LONG).show();
}else if(tabId.equals("2")){
Toast.makeText(Chapter6TabHostActivity.this, "你选择:"+tabId, Toast.LENGTH_LONG).show();
}else if(tabId.equals("3")){
Toast.makeText(Chapter6TabHostActivity.this, "你选择:"+tabId, Toast.LENGTH_LONG).show();
}
}
});
}
}
如果想在tab页面中添加其他组件的话,需要嵌套布局组件view对象
如上: <FrameLayout
android:id="@+id/view1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/phone1"/>
</FrameLayout>