공부방/Android

How to android tabItem textView in tabLayout change text style bold programmatically (안드로이드 tablayout tabItem textview bold처리 코드로 하기)

soycrab 2020. 9. 3. 16:16
fun TabLayout.changeTabsFont(selectPosition: Int) {
    val vg = this.getChildAt(0) as ViewGroup
    val tabsCount = vg.childCount
    for (j in 0 until tabsCount) {
        val vgTab = vg.getChildAt(j) as ViewGroup
        vgTab.forEachIndexed { index, _ ->
            val tabViewChild = vgTab.getChildAt(index)
            if (tabViewChild is TextView) {
                tabViewChild.setTextBold(j == selectPosition)
            }
        }
    }
}

 

커스텀 폰트 적용하고 싶을시 

fun TextView.setTextBold(isBold: Boolean) {
    this.typeface = ResourcesCompat.getFont(this.context,if(isBold) R.font.yoon770 else R.font.yoon740)
}

해당 관련 내용은 아래 링크 참고

sweetcoding.tistory.com/167

 

기본  폰트 Bold 처리 변경시 

fun TextView.setTextBold(isBold: Boolean) {
    this.setTypeface(this.typeface, if(isBold) Typeface.BOLD else Typeface.NORMAL) 
}

 

 

사용 방법 

tabLayout.addOnTabSelectedListener(tabLayoutOnPageChangeListener)

private val tabLayoutOnPageChangeListener = object : TabLayout.OnTabSelectedListener {
        override fun onTabReselected(tabItem: TabLayout.Tab?) {}

        override fun onTabUnselected(tabItem: TabLayout.Tab?) {}

        override fun onTabSelected(tabItem: TabLayout.Tab?) {
            tabItem?.position?.let { 
                tabLayout.changeTabsFont(it)
            }
        }
    }

 

처음 화면 진입시 초기화를 해줘야 처음 탭이 Bold 처리가 되므로 

화면  시작시 

tabLayout.changeTabsFont(0)

을 호출해 주면 된다.

반응형