一、概念
盛放Tab的容器就是TabHost,TabHost的实现方法有两种:
1.继承TabActivity,从TabActivity中使用getTabHost()方法获取TabHost。各个Tab中的内容在布局文件中定义就行了。
2.不继承TabActivity ,在布局文件中定义TabHost()即可,但是,TabWidget的id必须是@android:id/tabs,FrameLayout@android:id/tabcontent。
二、案例
1.不继承TabActivity
继承普通Activity,<TabWidget>标签id必须为tabs、<FrameLayout>标签id必须为tabcontent.这个方式在通过findViewById获得TabHost之后,必须要调用setup方法。
<?xml version="1.0" encoding="utf-8"?>
<!-- TabHost必须包含一个 TabWidget和一个FrameLayout-->
<TabHost android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content">
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<!-- TabWidget的id属性必须为 @android:id/tabs-->
<TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<!-- FrameLayout的id属性必须为 @android:id/tabcontent-->
<FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:id="@+id/view1" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
<TextView android:id="@+id/view2" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
<TextView android:id="@+id/view3" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
java代码
public class TabHostTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取TabHost对象
TabHost tabHost = (TabHost) findViewById(R.id.tabhost);
// 如果没有继承TabActivity时,通过该种方法加载启动tabHost
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("第一个标签",
getResources().getDrawable(R.drawable.icon)).setContent(
R.id.view1));
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("第三个标签")
.setContent(R.id.view3));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("第二个标签")
.setContent(R.id.view2));
}
}