I'm trying to have a tabLayout with 3 differents TextColor based on 3 states that I'll do programmatically, basically the states will be CURRENT
, SEEN
, UNSEEN
and everything is dynamic.
The problem is that the base viewpager and more precisely tablayout allows only 2 states which are SELECTED
and UNSELECTED
. Not to mention the setCustomView, will add (create) a view instead of setting (update) the value and I end up stacking views...
I was thinking about overriding the TabLayout class or adding some kotlin extentions but dunno really where to start.
If you guys could point out some directions it would be greatly appreciated!
Thanks in advance.
Made it worked thanks to @Akaki pointing me in the right direction:
First created a method to change tabTextColor:
private fun changeTabTextColor(tabLayout: TabLayout?, index: Int, mainColor: Boolean) {
if (index in 0 until maxPosition) {
val tab = tabLayout?.getTabAt(index)
val sb = SpannableString(tab?.text)
val color =
if (mainColor) ContextCompat.getColor(ctx, R.color.main_text_color)
else ContextCompat.getColor(ctx, R.color.secondary_text_color)
sb.setSpan(ForegroundColorSpan(color), 0, sb.length, 0)
tab?.text = sb
}
}
I'm handling 2 colors here, but can add more if needed.
Second the crucial part is that setting the text will destroy the animation, so we need to handle it by ourselves in the ViewPager:
binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
tabLayout?.setScrollPosition(position, positionOffset, false)
}
override fun onPageSelected(position: Int) {}
})
That way the animation will remain.
Then I played with onTabSelected
and called the method changeTabTextColor
to fit my needs.