版权声明:本文为HaiyuKing原创文章,转载请注明出处!
前言
使用FragmentTabHost实现底部选项卡效果。
备注:该Demo主要是演示FragmentTabHost的一些设置和部分功能,实际中需要参考其他Demo。
效果图
代码分析
1、该Demo中采用的是FragmentTabHost的布局方案之一【命名为非常规布局写法】;【建议使用常规布局写法,见《FragmentTabHostTopDemo【FragmentTabHost固定宽度且居中】》】
2、未使用自定义的FragmentTabHost;【建议使用自定义的FragmentTabHost,见《FragmentTabHostUnderLineDemo【FragmentTabHost带下划线】》】
原因是FragmentTabHost切换时执行的是attach/detach,而不是show/hide。而atach触发的执行顺序:attach()->onCreateView()->onActivityCreated()->onStart()->onResume()
使用hide()方法只是隐藏了fragment的view并没有将view从viewtree中删除,随后可用show()方法将view设置为显示。
3、ContactFragment演示的是:使用FragmentTabHost时,Fragment之间切换时每次都会调用onCreateView方法,导致每次Fragment的布局都重绘,无法保持Fragment原有状态。
小结:对于2和3,都是解决切换fragment的时候重载的问题,两种方案各有利弊,选择其中一个即可。
4、演示设置选项卡区域的自定义宽度和高度;
5、演示初始化时、切换时传参;【切换时传参,可能一般用不到】
6、自定义选项卡子项类【获取底部选项卡的布局实例并初始化设置、更新文字颜色】;【这个思路参考别人的,思路比较好】【更新每个选项卡的背景需要额外写另外的方案,见《FragmentTabHostTopDemo【FragmentTabHost固定宽度且居中】》】
7、演示点击选项卡子项不切换到相应的fragment,而是打开一个新的界面;【用作个别情况】
使用步骤
一、项目组织结构图
注意事项:
1、 导入类文件后需要change包名以及重新import R文件路径
2、 Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖
二、导入步骤
将选项卡子项布局文件tab_bottom_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" 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/bottomtab_checkedTextView" android:tag="tag1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="" android:textSize="@dimen/tab_text_size" android:textColor="@color/tab_text_normal" android:textAlignment="center" /> </RelativeLayout>