Chol Chol - 9 months ago 118
Android Question

Custom selected tab text color in SlidingTabLayout

I'm using the SlidingTabLayout from google (

It works well, but what I want it is to put the selected title in bold and with a different color...

Regarding this post :
Custom unselected tab text color in SlidingTabLayout

I make a text_tab.xml in drawable with the selector:

<selector xmlns:android="">
<item android:color="@android:color/selected" android:state_selected="true" />
<item android:color="@android:color/unselected" />

When in the populateTabStrip() method I put


The color is always the one of unselected...

I'm probably doing something wrong, or maybe there is another way to customise the selected tab title.

Someone has an idea?



The problem is, sliding layout do not set item's state as selected. Here is my approach to solve the problem.

1) Create COLOR selector (ColorStateList) for your view. You can imagine it this way:


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
  <item android:color="@color/white" android:state_selected="true"/>
  <item android:color="@color/black"/>

2) Place created selector to your item's view textColor (or other required) attribute:

  ... />

3) Do this changes in file

View oldSelection = null; // new field indicating old selected item

// method to remove `selected` state from old one
private void removeOldSelection() { 
    if(oldSelection != null) {

// improve method scrollToTab() as follows
private void scrollToTab(int tabIndex, int positionOffset) {
    final int tabStripChildCount = mTabStrip.getChildCount();
    if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {

    View selectedChild = mTabStrip.getChildAt(tabIndex);
    if (selectedChild != null) {

        if(positionOffset == 0 && selectedChild != oldSelection) { // added part
            oldSelection = selectedChild;

        int targetScrollX = selectedChild.getLeft() + positionOffset;

        if (tabIndex > 0 || positionOffset > 0) {
            // If we're not at the first child and are mid-scroll, make sure we obey the offset
            targetScrollX -= mTitleOffset;

        scrollTo(targetScrollX, 0);

private void populateTabStrip() {
    removeOldSelection(); // add those two lines
    oldSelection = null;