Skip to content

Instantly share code, notes, and snippets.

@artworkad
Last active March 14, 2017 17:28
Show Gist options
  • Save artworkad/49650360eab05c8deebd373a11fdd639 to your computer and use it in GitHub Desktop.
Save artworkad/49650360eab05c8deebd373a11fdd639 to your computer and use it in GitHub Desktop.
Android TabLayout with icons and color state list
/**
* IconTabLayout is an extension of TabLayout and enables us to use icons instead of
* text for the tabs. To reuse a single icon for different states we simply tint it
* with color state list. I use vector drawables for icons.
*/
class IconTabLayout : TabLayout {
private var viewPager: ViewPager? = null
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr)
override fun onAttachedToWindow() {
if (viewPager == null) {
if (parent is ViewPager) viewPager = parent as ViewPager
}
super.onAttachedToWindow()
}
override fun setupWithViewPager(viewPager: ViewPager?, autoRefresh: Boolean) {
this.viewPager = viewPager
super.setupWithViewPager(viewPager, autoRefresh)
}
override fun addTab(@NonNull tab: Tab, position: Int, setSelected: Boolean) {
if (viewPager != null && viewPager!!.adapter is TabPagerAdapter) {
val icon: Drawable = DrawableCompat.wrap((viewPager!!.adapter as TabPagerAdapter).getPageIcon(context, position))
DrawableCompat.setTintList(icon.mutate(), ContextCompat.getColorStateList(context, R.color.tab_color))
tab.icon = icon
}
super.addTab(tab, position, setSelected)
}
}
/**
* TabPagerAdapter provides fragments and icons for TabLayout
*/
class TabPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount(): Int = 2
override fun getItem(position: Int): Fragment = when (position) {
0 -> YourFragment.newInstance()
else -> YourFragment.newInstance()
}
fun getPageIcon(context: Context, position: Int): Drawable = when (position) {
0 -> ContextCompat.getDrawable(context, R.drawable.ic_whatshot)
else -> ContextCompat.getDrawable(context, R.drawable.ic_local_bar)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment