TabLayout selected Tab icon is not selected on start up

The correct answer for tab selection in TabLayout would be:

TabLayout.Tab currentTab = mTabs.getTabAt(selectedTab);
if (currentTab != null) {
    View customView = currentTab.getCustomView();
    if (customView != null) {
        customView.setSelected(true);
    }
    currentTab.select();
}

where currentTab.select() will move the indicator to the selected tab, when customView.setSelected() will make all the items in the custom view set their selected states from the selectors look selected.


Try this:

tabLayout.getTabAt(yourInitialPosition).getCustomView().setSelected(true);


I used in my tabLayout the xml selector for the icons with the following states:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/icon_ajuda_off"/>
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/icon_ajuda_on"/>
<item android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/icon_ajuda_on"/>
<item android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/icon_ajuda_on"/>

and in the code:

private int[] tabIcons = {R.drawable.ic_tab_sites, R.drawable.ic_tab_help,
        R.drawable.ic_tab_profile, R.drawable.ic_tab_notification, R.drawable.ic_tab_search};

if (tabLayout != null) {
    for (int i = 0; i < 5; i++) {
        tabLayout.getTabAt(i).setIcon(tabIcons[i]);
    }
}

It might help.