美文网首页
FragmentTabHost的使用

FragmentTabHost的使用

作者: 一笨正经的小屁孩 | 来源:发表于2020-06-29 20:55 被阅读0次
    FragmentTabHost

    前言

    现在很多APP的主页面都采用底部页签的样式,点击不同的底部标签能够在当前页面显示不同内容,实现的手段有很多种,今天我们来说一说使用FragmentTabHost+Fragment构建底部页签和页面内容。

    思考

    开始之前,我们先来思考一下,如果我们不使用FragmentTabHost构建主页面,那么这样的效果该怎么实现呢?

    可能会想到不同页签对应的页面可以使用不同的Fragment,也就是需要一个FrameLayout来装这些Fragment,这样,主页面的布局就是上面一大部分是一个大大的FrameLayout,底部因为需要显示不同的页签,页签是横向排列的,而且一般是等分的,这就可以使用LinearLayout来实现了,每个页签里面可能会显示图片和文字,图片和文字可能还会有选中状态,我们可以在点击到哪个页签时,再设置哪个页签的选中状态,然后切换不同的Fragment...

    这可能是我们第一时间想到的最简单的实现方案,接下来我们来看一看FragmentTabHost,看看它和我们想的“最简单实现方案”有什么不同?

    使用FragmentTabHost

    如果你使用androidx,它位于androidx.fragment.app包下,如果不使用androidx,那么它位于android support包中,这标志着你需要引入android support包的依赖,可以是v4包,也可以是v13包...

    不过在androidxsupport-v13包中,FragmentTabHost类都被标记为了废弃,官方不建议我们使用它了,但是不妨碍我们对它的学习,后续我们可以借鉴它的实现思路或者代码封装我们自己的FragmentTabHost(因为原生的FragmentTabHost可能满足不了我们的需求)。

    构建布局文件

    开发页面的第一步一般都是构建布局文件,我们来看看使用FragmentTabHost的主页面布局文件是什么样的?

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.fragment.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <!--Fragment显示区域,注意它的id-->
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />
    
            <!--内容和底部标签分割线-->
            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/colorPrimary" />
    
            <!--底部页签显示区域,注意它的id-->
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </androidx.fragment.app.FragmentTabHost>
    

    上面的布局文件中,我们使用FragmentTabHost来做根布局,由于FragmentTabHost继承自TabHostTabHost又继承自FrameLayout,所以我们不能把子View直接放在它里面,这会造成布局的遮挡,这里我们使用了LinearLayout,把它设置成竖直方向排列,里面用FrameLayout来显示Fragment,用TabWidget显示底部页签。需要注意两点:

    • 显示FragmentFrameLayout的id是@android:id/tabcontent
    • 显示底部页签的TabWidgetid是@android:id/tabs

    要想使用FragmentTabHost,就必须使用这两个系统定义的id,不然程序会crash,因为在TabHost中会通过findViewById找这两个View,找不到的话会抛出异常。

    从布局上看我们发现这跟我们前面想的“最简单实现方案”有些相似,确实,FragmentTabHost就是这种思路的封装实现。

    初始化FragmentTabHost

    完成布局文件之后,我们就需要在代码中设置FragmentTabHost了:

    /* 内容 */
    private val fragments = arrayOf(
       StarFragment::class.java,
       PlazaFragment::class.java,
       ChatFragment::class.java,
       MeFragment::class.java
    )
    
    // container是FragmentTabHost,初始化FragmentTabHost
    container.setup(this, supportFragmentManager, android.R.id.tabcontent)
    for (index in fragments.indices) {
       val tabSpec = container.newTabSpec(index.toString())
       // 设置底部标签View
       tabSpec.setIndicator(provideTabView(index))
       // FragmentTabHost添加Context和TabSpec
       container.addTab(tabSpec, fragments[index], null)
    }
    

    我们来逐行分析上面这段初始化FragmentTabHost的代码...

    container.setup(this, supportFragmentManager, android.R.id.tabcontent)
    

    container就是FragmentTabHost这个根布局容器,调用setup方法,这个方法有三个参数,第一个参数是Context,传入当前activity就可以了,第二个参数是FragmentManager,通过FragmentActivity#getSupportFragmentManager()方法就可获取到,第三个参数需要传入显示Fragment的容器的id,也就是布局文件中设置id为tabcontentFrameLayout

    for(index in fragments.indices)
    

    对需要显示的Fragment集合进行遍历,以初始化底部页签和对应的内容。

    val tabSpec = container.newTabSpec(index.toString())
    

    通过调用newTabSpec方法实例化一个TabSpecnewTabSpec需要传入一个tag参数,我们可以理解这是为每个页签和内容设置一个tag,实际上FragmentTabHost内部也会用它从FragmentManager中获取Fragment,所以它也是每个Fragmenttag,这里我们直接使用数组索引来当tag了。

    TabSpec还包含两个策略实例字段IndicatorStrategy mIndicatorStrategyContentStrategy mContentStrategy,一个表示底部页签View显示策略,一个表示页签对应的内容显示策略,不过这里的内容显示策略我们用不到,它只在TabHost中用到了,FragmentTabHost中并没有使用这个内容显示策略。

    tabSpec.setIndicator(provideTabView(index))
    

    设置底部页签View显示策略,传入我们想要显示的底部页签View,这里我们定义的每个页签样式如下:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        tools:ignore="SpUsage">
    
        <ImageView
            android:id="@+id/ivTab"
            android:layout_width="25dp"
            android:layout_height="25dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/tvTab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:textColor="@android:color/black"
            android:textSize="12dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/ivTab" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    包含一个ImageView和一个TextView

    provideTabView()方法实现如下:

    /* 底部标签图片,它们是个selector */
    private val tabImages = arrayOf(
       R.drawable.selector_bottom_tab_star,
       R.drawable.selector_bottom_tab_plaza,
       R.drawable.selector_bottom_tab_chat,
       R.drawable.selector_bottom_tab_me
    )
    
    /* 底部标签文本 */
    private val tabTexts = arrayOf(
       R.string.text_bottom_tab_star,
       R.string.text_bottom_tab_plaza,
       R.string.text_bottom_tab_chat,
       R.string.text_bottom_tab_me
    )
    
    private fun provideTabView(index: Int): View =
            layoutInflater.inflate(R.layout.view_bottom_tab, null).apply {
                ivTab.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, tabImages[index]))
                tvTab.text = resources.getString(tabTexts[index])
            }
    

    底部页签的图片是selectorselector样式如下:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/img_star_p" android:state_selected="true" />
        <item android:drawable="@drawable/img_star" />
    </selector>
    

    container.addTab(tabSpec, fragments[index], null)

    设置底部页签和内容(即Fragment),addTab()方法有三个参数,第一个参数是TabSpec,第二个参数是Class类型,也就是FragmentClass类型,FragmentTabHost内部会通过反射获取Fragment实例,第三个参数是个Bundle,我们可以通过它给Fragment传递参数。

    做完上面这些,主页面的构建就算完成了,下面需要做的就是完善每个Fragment的逻辑了。

    总结

    FragmentTabHost使用还是比较简单的,只需要注意上面提到的几个注意点就没问题,不过FragmentTabHost中的Fragment生命周期可能不是你想要的,它的生命周期是这样的:切换页签的时候,Fragment都会执行onDestroyViewonCreateView,这就意味着每次切换页签,Fragment里面的View都会被销毁,显示的页面View会被重建,如果你不想要Fragment生命周期是这样的该怎么办呢?哈哈,不好意思,FragmentTabHost做不到,只要你用FragmentTabHostFragment生命周期就是这样的,但是有了FragmentTabHost源码,我们可以在其基础上改一改实现一个我们自己的FragmentTabHost,这部分我们下回再说。

    相关文章

      网友评论

          本文标题:FragmentTabHost的使用

          本文链接:https://www.haomeiwen.com/subject/aswafktx.html