Last active
March 14, 2017 17:28
-
-
Save artworkad/49650360eab05c8deebd373a11fdd639 to your computer and use it in GitHub Desktop.
Android TabLayout with icons and color state list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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