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

后端 未结 11 2846
南笙
南笙 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:41

    In my case, setTypeface doesn't work right after tab init so I need to use post method to wait TextView laid out then setTypeface

    tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabReselected(tab: TabLayout.Tab?) {
        }
    
        override fun onTabUnselected(tab: TabLayout.Tab?) {
            tab?.let {
                setStyleForTab(it, Typeface.NORMAL)
            }
        }
    
        override fun onTabSelected(tab: TabLayout.Tab?) {
            tab?.let {
                setStyleForTab(it, Typeface.BOLD)
            }
        }
    
        fun setStyleForTab(tab: TabLayout.Tab, style: Int) {
            tab.view.children.find { it is TextView }?.let { tv ->
                (tv as TextView).post {
                    tv.setTypeface(null, style)
                }
            }
        }
    })
    

提交回复
热议问题