您的位置:首页 > 移动开发 > Android开发

Android FragmentTabHost使用

2015-08-04 10:13 781 查看
Android FragmentTabHost使用

布局文件

初始化FragmentTabHost

解释

布局文件

FrameLayout的realtabcontent是内容界面,放在FragmentTabHost上面tab导航就显示在其下面,放在fragmentTabHost下面就显示在其上面。但是放在上面的时候得注意高度不能为match_parent,否则导航标签不显示,放在下面可以是match_parent。而不管放在上面还是下面tabcontent的FrameLayout的宽高必须为0。

[code]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" /> 

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"/>
    </android.support.v4.app.FragmentTabHost>
 <!--     <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" /> -->
</LinearLayout>


初始化FragmentTabHost

[code]mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("0").setIndicator("tab1"), TabFrg1.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("1").setIndicator("tab2"), TabFrg2.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("2").setIndicator("tab3"), TabFrg3.class, null);


导航标签通常是一个view,view中放置一个图标和文字

TabSpec spec = mTabHost.newTabSpec(“xxx”).setIndicator(view);

解释

我的xml布局文件下面有2个FrameLayout,一个是引用的@android:id/tabcontent,一个是自己定义的id,Google官方的例子也是这样写得,有人可能和我一样有疑问——为什么要这样写?这里给出答案:

android的tabcontent就是对应着TabHost.TebSpec中的setContent()方法的参数(int ViewId)或者Intent或者TabHost.TabContentFactory,分别对应着view视图、在tab的FrameLayout中启动一个Activity【3.0已废弃】、由TabContentFactory对象产生的View。

而Fragment是3.0之后的版本中加进去的,所以@android:id/tabcontent的标签没有实现这个功能,所以要设置FragmentTabHost里面的fragment,就需要自己定义一个标签,并让上面的@android:id/tabcontent在视图上不可见,于是我们看到它的宽高都是0。其实这个布局就是一个自定义的内容布局再加上一个原始的TabHost,而原始的TabHost的tabContent没有显示,只显示了tab导航,我们在给mTabHost初始化时指定它的实际tabContent内容,使用该tab导航和realTabContent来实现tabHost功能。给FragmentTabHost添加tabSpec的时候设置setIndicator既可,不需要setContent,而在添加(addTab)的时候指定Fragment,该fragment就是用来填充tabContent的。不能使用以下三种形式。

[code]TabSpec spec1 = mTabHost.newTabSpec("1").setIndicator("tab1").setContent(new Intent(this, TabFrg1.class));
TabSpec spec2 = mTabHost.newTabSpec("2").setIndicator("tab2").setContent(R.layout.abc_action_bar_decor);
TabSpec spec3 = mTabHost.newTabSpec("3").setIndicator("tab3").setContent(contentFactory);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: