I'm using the new support TabLayout from Android. The thing is that I wanted to use selectors to change the icon when a tab is selected.
I've been looking into the source code and it seems to me that the it never changes the state of the view (and for that reason I can't use the selector).
Does anyone knows some workaround?
Thank you!
Assume your my_selector.xml is,
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/icon_on" android:state_selected="true"/>
<item android:drawable="@drawable/icon_off"/> <!-- default -->
</selector>
then you can call setIcon directly,
tab.setIcon(R.drawable.my_selector);
Verified with 'com.android.support:design:22.2.0'.
I found that when I first set the custom view for each tab in the TabLayout I need to set the first one (index 0) as selected.
TabLayout toolbarTabLayout = (TabLayout) findViewById(R.id.tabs);
toolbarTabLayout.setupWithViewPager(mViewPager);
toolbarTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
toolbarTabLayout.setTabMode(TabLayout.MODE_FIXED);
toolbarTabLayout.setTabTextColors(R.color.colorPrimary, R.color.white);
// Iterate over all tabs and set the custom view
for (int i = 0; i < toolbarTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = toolbarTabLayout.getTabAt(i);
View v=mSectionsPagerAdapter.getTabView(i);
// no tabs are actually selected at start, this will make sure the
// selector for the colors comes in right when initialized
if (i==0)
v.setSelected(true);
tab.setCustomView(v);
}
This seems to force the first tab as selected when the custom view is applied. It really feels like a hack, hopefully someone else will figure out the real issue and propose a better fix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With