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.
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
}