Skip to content Skip to sidebar Skip to footer

Android - Tablayout With Custom View Tabs - Drawable Selector Cannot Be Applied

I am trying to set up custom tabs in a tablayout using compile 'com.android.support:design:25.3.1' in gradle. I want to use selectors so that when a tab is clicked it changes based

Solution 1:

I'm using support library 27.1.1 and facing the same problem. After some research I found that the state_selected must be defined clearly. See code below:

<selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@drawable/ic_chat_disabled"android:state_selected="false"/><itemandroid:drawable="@drawable/ic_chat_enabled"android:state_selected="true"/></selector>

android:state_selected="false" is must have!

Solution 2:

i ended up dropping the selector approach and just getting my customView from the tab. then i can change its view elements. i had a set of images in an array for selected and another for unselected.

then when the tabs switched i switch between the images based on tab position:

@OverridepublicvoidonTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        ImageViewiv= (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
        TextViewtv= (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

        iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId_selected[tab.getPosition()]));
        tv.setTextColor(ContextCompat.getColor(this, R.color.black));

    }
@OverridepublicvoidonTabUnselected(TabLayout.Tab tab) {
    ImageViewiv= (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
    TextViewtv= (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

    iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId[tab.getPosition()]));
    tv.setTextColor(ContextCompat.getColor(this, R.color.tabs_default_text));

}

@OverridepublicvoidonTabReselected(TabLayout.Tab tab) {

}

Post a Comment for "Android - Tablayout With Custom View Tabs - Drawable Selector Cannot Be Applied"