7.1.5 选项卡结合案例详解
选项卡是通过TabHost和TabActivity一起实现的,TabHost是Android中很常用的布局之一,它的标签可以有文本和文本图片样式。点击不同标签还可以切换标签。TabHost类的继承图如下:
java.lang.Object
?android.view.View
?android.view.ViewGroup
?android.widget.FrameLayout
?android.widget.TabHost
android.widget.TabHost继承了android.widget.FrameLayout框架布局类。下面是一个文本图片选项卡例子,如图7-10所示。

图7-10 TabHost1
代码请参考代码清单7-11,完整代码请参考chapter7_1工程中Tab1代码部分。
【代码清单7-11】
public class Tab1 extends TabActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TabHost tabHost = getTabHost();LayoutInflater.from(this).inflate(R.layout.tab1_layout,tabHost.getTabContentView(), true);tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1",getResources().getDrawable(R.drawable.redimage)).setContent(R.id.view1));tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab2",getResources().getDrawable(R.drawable.yellowimage)).setContent(R.id.view2));tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3").setContent(R.id.view3));}}<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/view1" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/tab1"/> <TextView android:id="@+id/view2" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/tab2"/> <TextView android:id="@+id/view3" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/tab3"/></LinearLayout>

public class Tab2 extends TabActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TabHost tabHost = getTabHost();tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("城市列表").setContent(new Intent(this, ListView_1.class)));tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("城市展示").setContent(new Intent(this, ListViewIcon_3.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));}}