Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the color of icon of the selected tab of TabLayout?

I'm using a TabLayout with a ViewPager and I'm wondering how I can most efficiently change the color of the icon of the selected tab in the TabLayout.

A perfect reference for how this is implemented is Google's Youtube app. On the main page, there are four icons that are colored dark gray. When a specific tab is selected, the tab's icon becomes white.

Without any third party libraries, how can I achieve the same effect?

One possible solution is apparently with selectors. But in that case, I would have to find both a white and a gray version of the icon and then switch the icon when the tab becomes selected or deselected. I'm wondering if there's a more effective method where I can just highlight the icon color or something. I haven't been able to find this in any tutorial.

EDIT

The solution that I mention directly above requires the use of two drawables for each tab's icon. I'm wondering if there's a way I can do it programmatically with ONE drawable for each tab's icon.

like image 351
waylonion Avatar asked Jan 02 '16 02:01

waylonion


People also ask

How do I add an icon to tabLayout?

TabLayout is introduced in the design support library to implement tabs. Tabs are created using the newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively.

How do I change the icon size on my Android tablet?

Change icon size on Android devices by going to Settings > Wallpaper & style > App grid and changing it to a grid with fewer or more columns and rows.


1 Answers

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);                 }             }     ); 
like image 174
Cristian Hoyos Avatar answered Sep 18 '22 14:09

Cristian Hoyos