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

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

    This is a Kotlin code for this solution

     for (i in 0..tabLayout.tabCount){
            val tab:TabLayout.Tab? = tabLayout.getTabAt(i)
            if (tab != null){
                val tabTextView:TextView = TextView(this)
                tab.customView = tabTextView
    
                tabTextView.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
                tabTextView.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
    
                tabTextView.text = tab.text
    
                if (i == 0){
                    // This set the font style of the first tab
                    tabTextView.setTypeface(null,BOLD)
                    
                }
                if (i == 1){
                    // This set the font style of the first tab
    
                    tabTextView.setTypeface(null,NORMAL)
                    
                }
            }
        }
        tabLayout!!.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewPager.currentItem = tab!!.position
    
                val text:TextView = tab.customView as TextView
    
                
                text.setTypeface(null,BOLD)
                
    
    
            }
    
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                val text:TextView = tab?.customView as TextView
    
    
                text.setTypeface(null,NORMAL)
                
    
            }
    
            override fun onTabReselected(tab: TabLayout.Tab?) {
    
            }
    
        })
    

提交回复
热议问题