FragmentTabHost 用法


一、FragmentTabHost结构如下图:

FragmentTabHost 用法

FragmentTabHost 包含两个内容:TabWidget和FrameLayout。
标准的FragmentTabHost是TabWidget在上面,FrameLayout在下面。
如果想要制作TabWidget在下面的效果,可以在布局文件中手动添加一个FrameLayout,并将FragmentTabHost 中的FrameLayout 的宽高设为0即可。不能省略掉FragmentTabHost 中的FrameLayout。

  • 注意:FragmentTabHost、TabWidget、FrameLayout的id必须是使用 android:id/XXX,不能使用自定义的id即 +id/ 。

二、XML文件的配置

xml文件的示例代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.solo.chat.HomeActivity" >

    <FrameLayout
        android:id="@+id/activity_home_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

    <!-- 注意:FragmentTabHost中的组件id都必须用系统id -->
    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TabWidget 
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ></TabWidget>
        
        <FrameLayout 
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            ></FrameLayout>
        
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

这个布局即是TabWidget在下,FrameLayout在上。跟微信的效果一致。

三、代码中的配置

使用FragmentTabHost 分为三个步骤:

  1. 初始化FragmentTabHost
  2. 新建TabSpec
  3. 将TabSpec添加进FragmentTabHost

代码如下:

// 1.初始化FragmentTabHost
FragmentTabHost tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(),R.id.activity_home_container); 

// 2.新建TabSpec(小标签),并setIndicator
TabSpec tabSpec = tabHost.newTabSpec(TAG_CHAT);
chatIndicator = new TabIndicatorView(this);
	//下面三个方法是项目中自定义方法
	chatIndicator.setIcon(R.drawable.tab_icon_chat_normal,R.drawable.tab_icon_chat_focus);
	chatIndicator.setTitle("消息");
	chatIndicator.setUnReadCount(0);
tabSpec.setIndicator(chatIndicator);

// 3.将TabSpec添加进FragmentTabHost
// 参数1:FragmentTabHost 参数2:要显示内容的类名 参数3:要传递的Bundle参数
tabHost.addTab(tabSpec, MyFragment.class, null);

//去掉分割线
tabHost.getTabWidget().setDividerDrawable(android.R.color.white);

//初始化tab选中
tabHost.setCurrentTabByTag(TAG_CHAT);
chatIndicator.setSelected(true);   //自定义的方法

//设置Tab点击切换监听
tabHost.setOnTabChangedListener(this);

以上就是FragmentTabHost的使用方法。