Change tabs text color in TabLayout to different colors programmatically

后端 未结 5 851
刺人心
刺人心 2021-01-18 14:02

I have 7 dates tabs in my screen, when tab selected, the text is black in color; while other select-able tabs are white in color. If the date falls on another month, I want

5条回答
  •  情书的邮戳
    2021-01-18 14:08

    Best practices is used material TabLayout with ViewPager2.

    dependencies {
        // ...
        implementation 'com.google.android.material:material:1.0.0'
        // ...
    }
    

    In XML attributes

    
                
                
            
    

    In Kotlin

    //set your adapter
    //view_pager.adapter =  WebViewFragmentTabAdapter(supportFragmentManager, lifecycle)
    TabLayoutMediator(tab_layout, view_pager) { tab, position ->
        tab.text = AppDataInstance.navigationTab[position].name
        view_pager.setCurrentItem(tab.position, true)
    }.attach()
    
    // in case you need to set color programmatically
    (tab_layout as TabLayout).setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
    (tab_layout as TabLayout).setSelectedTabIndicatorColor(ContextCompat.getColor(mContext, R.color.white))
    (tab_layout as TabLayout).setTabTextColors(ContextCompat.getColor(mContext, R.color.white),
                    ContextCompat.getColor(mContext, R.color.white))
    

提交回复
热议问题