fragment中加入tabhost以及修改TabWidget

现在的应用的数据量越来越多,应用都需要在fragment中嵌入选项卡对信息进行分类,例如知乎、简述
知乎截图
但是在fragmen中嵌入tabHost,我不支持用其他的方法去实现仿按钮,因为多少会有点别扭


闲话少说,今天说的是在fragment里加入tabHost控件,因为fragment的控制文件class是只能继承一个类,所有无法再去继承TabActivity。我们需要采取的解决办法是:
现在fragment的xml中加入tabHost控件。代码如下:

</TabWidget>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dip"
            android:background="@color/tab_text_color"/>
        <ScrollView
            android:fillViewport="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <FrameLayout

            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">



            <LinearLayout
                android:orientation="vertical"
                android:id="@+id/my_info"
                android:layout_width="match_parent"
                android:layout_height="match_parent"></LinearLayout>
        </FrameLayout>
</ScrollView>
    </LinearLayout>

</TabHost>

看到上面的代码中,我们要注意一点的是,TabHost的Id不是写上androidjdk的android/id/tabhost,而是我们自己定义一个id,然后其余的和正常的相同,然后再在class中这么用:

priavte TabHost tabhost;
 tabhost.setup();
tabhost=(TabHost)findViewById(R.id.tabhost);
 TabHost.TabSpec tab1 = tabhost.newTabSpec("A").setIndicator(getString(R.string.my_page))
                .setContent(R.id.my_page);

        tabhost.addTab(tab1);
        TabHost.TabSpec tab2 = tabhost.newTabSpec("B").setIndicator(getString(R.string.my_infomation))
                .setContent(R.id.my_info);
        tabhost.addTab(tab2);
        tabhost.setCurrentTab(1);
        tabhost.setCurrentTab(0);
        TextView tx = (TextView) (tabhost.getTabWidget().getChildAt(0)).findViewById(android.R.id.title);
        tx.setTextColor(Color.WHITE);
        tx.setPadding(0, 15, 0, 0);
        tx = (TextView) (tabhost.getTabWidget().getChildAt(1)).findViewById(android.R.id.title);
        tx.setTextColor(Color.WHITE);
        tx.setPadding(0, 15, 0, 0);

第一点一定要记得初始化tabhost.tabhost.setup();然后就可以正常使用了,另外,就是上面代码里还有怎么去更改和控制TabWidget里的字体和图片的方法。控制图片就是吧上面的gettitle()改成getIcon就行了

猜你喜欢

转载自blog.csdn.net/lansus/article/details/49360845