1. TabHost
随便找了几篇讲解
http://blog.csdn.net/gdgydxyu/article/details/9054439
http://blog.csdn.net/miklon/article/details/12713093
http://blog.csdn.net/shulianghan/article/details/18233209
http://android.blog.51cto.com/268543/315208/
我觉得,要实现TabHost+ViewPager关键是了解TabHost的布局
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<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_content"
android:padding="5dp" />
</LinearLayout>
</TabHost>
同时还有两个知识要知道:1. TabSpec的view有一种设置方式是setContent( Intent inten),使用意图。2. 点击标签时触发事件是TabHost注册了OnTabChangedListener,并实现了onTabChanged(String tabId)方法。
2. ViewPager
参考的文章
http://blog.csdn.net/wangjinyu501/article/details/8169924
这里要知道页卡之间左右滑动实际上是ViewPager对象使用setOnPageChangeListener注册了OnPageChangeListener,并实现了onPageSelected(int position)方法。
3. 混合使用
参考文章
http://blog.csdn.net/qjlhlh/article/details/7788444
http://www.cnblogs.com/xingyyy/p/3283759.html
主要想法是用TabHost做容器,并使用TabHost的标签,但是不使用TabSpec显示页卡内容,也就是TabHost的Layout布局中,不使用FrameLauyot部分,而是添加一个ViewPager,变成如下:
<?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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TabWidget>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<!-- 将tabhost的tabcontent隐藏,用viewPage填充 -->
<FrameLayout
android:id="@android:id/tabcontent"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
</TabHost>
然后,ViewPager中加载各个页卡的view。
步骤类似四部曲:
1. 初始化标签,主要是TabHost.Tabspec使用setIndicator()方法。由于TabSpec没有用到,所以TabSpec的view可以为空view。
2. 初始化ViewPager,设置各个页卡的view。
3. 实现TabHost的标签点击事件(注册OnTabChangeListener接口实现onTabChanged(String tabId)方法),同时在点击标签时要切换下面的ViewPager
4. 实现ViewPager的页卡滑动切换事件,同时在页卡切换时要改变同时改变Tabhost上面的标签。