Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabLayout selected Tab icon is not selected on start up

I'm using a TabLayout for Tabbed navigation in my app. I have a really weird issue with it, I have created 4 tabs using this code:

private int[] tabIcons = {R.drawable.navigation_timeline_icon_selector, R.drawable.navigation_feed_icon_selector,
        R.drawable.navigation_messages_icon_selector, R.drawable.navigation_notification_icon_selector};

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

Each of the items in tabIcon is a selector with selected and non-selected states. All icon selectors are configured as follows:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/navigation_timeline_selected_icon" android:state_selected="true"/>
      <item android:drawable="@drawable/navigation_timeline_selected_icon" android:state_pressed="true"/>
      <item android:drawable="@drawable/navigation_timeline_icon" />
</selector>

The problem is that when the application starts the first selected tab (index 0) does not use the selected state icon. Instead it uses the non-selected state.

To be more explanatory here is a screenshot of the issue, on first start my tab looks like this:

enter image description here

when instead it should be like this:

enter image description here

After I change a page all the icons come back to full functionality, and the selected states are selected properly.

I tried to use the TabLayout.Tab select() method but the result is the same the icon that is used is the not selected icon.

Does someone know what I can do to fix it?

like image 558
Emil Adz Avatar asked Dec 21 '15 09:12

Emil Adz


1 Answers

Try this:

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

like image 109
emirua Avatar answered Sep 30 '22 02:09

emirua