How do I change the color of icon of the selected tab of TabLayout?
I found a way that can be easy.
viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.setOnTabSelectedListener( new TabLayout.ViewPagerOnTabSelectedListener(viewPager) { @Override public void onTabSelected(TabLayout.Tab tab) { super.onTabSelected(tab); int tabIconColor = ContextCompat.getColor(context, R.color.tabSelectedIconColor); tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN); } @Override public void onTabUnselected(TabLayout.Tab tab) { super.onTabUnselected(tab); int tabIconColor = ContextCompat.getColor(context, R.color.tabUnselectedIconColor); tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN); } @Override public void onTabReselected(TabLayout.Tab tab) { super.onTabReselected(tab); } } );
This can be done very simply, entirely in xml.
Add one line to your TabLayout in your xml, app:tabIconTint="@color/your_color_selector"
, as below:
<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIconTint="@color/your_color_selector" app:tabIndicatorColor="@color/selected_color"/>
Then, create a color selector file (named "your_color_selector.xml" above) in res/color directory:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/selected_color" android:state_selected="true"/> <item android:color="@color/unselected_color"/></selector>
This assumes you have 2 colors, "selected_color" and "unselected_color" in your colors.xml file.
private void setupTabIcons() { tabLayout.getTabAt(0).setIcon(tabIcons[0]); tabLayout.getTabAt(1).setIcon(tabIcons[1]); tabLayout.getTabAt(2).setIcon(tabIcons[2]); tabLayout.getTabAt(3).setIcon(tabIcons[3]); tabLayout.getTabAt(0).getIcon().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN); tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN); tabLayout.getTabAt(2).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN); tabLayout.getTabAt(3).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { tab.getIcon().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN); } @Override public void onTabUnselected(TabLayout.Tab tab) { tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN); } @Override public void onTabReselected(TabLayout.Tab tab) { } });}