How do I change the text style of a selected tab when using tabLayout?

后端 未结 11 2845
南笙
南笙 2021-02-19 07:57

I want to make the text of a selected tab bold. How can I do this either through xml or java code, whatever is easier.

11条回答
  •  死守一世寂寞
    2021-02-19 08:31

    I applied hoi's answer which is written above for default TabLayout with no custom view. It worked the best for me. But what I actually needed was to change the font family of the text inside the TabItem to a bolder one when a tab was selected. So following hoi's solution, I changed the code a bit to work for me. I am leaving this answer just in case if someone is trying to achieve something similar:

    private fun addOnTabSelectedListener() {
            tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) {
                    return
                }
    
                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    tab?.position?.let {
                        changeSelectedTabItemFontFamily(it, R.font.quicksand_medium)
                    }
                }
    
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    tab?.position?.let {
                        changeSelectedTabItemFontFamily(it, R.font.quicksand_bold)
                    }
                }
            })
        }
    
    private fun changeSelectedTabItemFontFamily(tabPosition: Int, @FontRes fontFamilyRes: Int) {
            val linearLayout = (this.tabLayout.getChildAt(0) as ViewGroup).getChildAt(tabPosition) as LinearLayout
            val tabTextView = linearLayout.getChildAt(1) as TextView
            val typeface = ResourcesCompat.getFont(context, fontFamilyRes)
            tabTextView.typeface = typeface
    }
    

提交回复
热议问题