Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use selectors to change icons with the new TabLayout

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!

like image 249
Fábio Carballo Avatar asked Jun 22 '15 09:06

Fábio Carballo


2 Answers

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'.

like image 152
Alpha Huang Avatar answered Nov 05 '22 00:11

Alpha Huang


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.

like image 26
BK- Avatar answered Nov 05 '22 02:11

BK-