版权声明:本文为HaiyuKing原创文章,转载请注明出处!

前言

使用FragmentTabHost实现顶部选项卡(居中且宽度非全屏)展现。

备注:该Demo主要是演示FragmentTabHost的一些设置和部分功能,实际中需要参考其他Demo。

效果图

FragmentTabHostTopDemo【FragmentTabHost固定宽度且居中】

代码分析

1、该Demo中采用的是FragmentTabHost的布局方案之一【命名为常规布局写法】;

2、未使用自定义的FragmentTabHost;【建议使用自定义的FragmentTabHost,见《FragmentTabHostUnderLineDemo【FragmentTabHost带下划线】》

3、演示更新文字颜色和背景;

4、切换回来后无法保持打开的网页,始终实现网址的首页。原因是FragmentTabHost切换时执行的是attach/detach,而不是show/hide。而atach触发的执行顺序:

attach()->onCreateView()->onActivityCreated()->onStart()->onResume()

而Demo中将webview.loadUrl()执行放到了onActivityCreated()方法中了。

解决方案:建议采用自定义的FragmentTabHost。【补充:还可以使用demo的fragment中onCreateView方法中的方案,两种方案各有利弊。】

使用步骤

一、项目组织结构图

FragmentTabHostTopDemo【FragmentTabHost固定宽度且居中】

FragmentTabHostTopDemo【FragmentTabHost固定宽度且居中】

注意事项:

1、  导入类文件后需要change包名以及重新import R文件路径

2、  Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

二、导入步骤

将选项卡子项布局文件tab_top_item.xml文件复制到项目中

<?xml version="1.0" encoding="utf-8"?>
<!-- 顶部选项卡布局 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/tab_bg_normal_top"
    android:gravity="center" >

    <!-- android:checkMark="?android:attr/listChoiceIndicatorMultiple"代表多选
         android:checkMark="?android:attr/listChoiceIndicatorSingle" 代表单选
         该属性不添加的话,不会显示方框或者圆点
       -->

    <!-- android:drawableTop的属性值使用drawable目录下的selector选择器 -->
    <!-- android:tag="tag1"用于checkedTextview的索引 -->

    <!-- 选项卡的内容(图片+文字)类似RadioButton -->
    <!--android:textAlignment="center" 文本居中-->
    <CheckedTextView
        android:id="@+id/toptab_checkedTextView"
        android:tag="tag1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text=""
        android:textSize="@dimen/tab_larger_text_size"
        android:textColor="@color/tab_text_normal_top"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:textAlignment="center"/>
</RelativeLayout>
tab_top_item

相关文章: