工作中常常使用到TabHost切换页面(一个界面看起来有多个页面显示)我们要注意两个概念:
1.TabHost是标签页的集合
2.TabSpec是标签
当我们得到TabHost对象后,可以使用addTab(tabspec)添加多个标签页.直接上实例代码..
<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" > <!-- 热门视频 --> <LinearLayout android:id="@+id/line1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="热门视频" /> </LinearLayout> <!-- 个人视频 --> <LinearLayout android:id="@+id/line2" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="个人视频" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost>
这里解释下..使用帧布局的目的是用于内容的显示...并且将设置权重为1,用来填满剩余的空间
然后我们可以在MainActivity中
第一步:我们要找到TabHost...
根据之前已经定义好的id,这里用的是自己定义的id.而不是系统的@android :id/tabhost,
mTabHost=(TabHost) findViewById(R.id.tabhost);
第二步:我们要找到TabWidget标签页和FrameLayout(这一步很重要)
mTabHost.setup();
这是TabHost内部的一个方法作用就是找到TabWidget标签页和FrameLayout,可以在源码中setup()可以查看,
注意的是TabWidget和FrameLayout分别对应的id是@android :id/tabs,@android :id/tabcontent
第三步:使用addTab(tabspec)添加标签页了
TabSpec tabSpec1=mTabHost.newTabSpec("tab1"); tabSpec1.setIndicator("热门视频",getResources().getDrawable(R.drawable.ic_launcher)); tabSpec1.setContent(R.id.line1); mTabHost.addTab(tabSpec1);
这里要说明下:为什么mTabHost.newTabSpec("tab1");为什么要加参数呢?
这是因为里面的参数表示标签页的唯一识别.
当然标签页中还没有内容,还要指定标签页的标题和内容,
tabSpec1.setIndicator();表示表明表项(表示了什么.代表了什么),这里传递图片和文字.
tabSpec1.setContent(R.id.line1);设置标签页的内容
效果显示如下:
简单吧。下一章介绍自定义的TabHost.