-3

I am using tabLayout to use tabs in my app. I want to change the background color & text color of selected tab. I am changing the background color of entire tabLayout by doing this

 android:background="@color/colorAccent"

and changing textcolor and selectedtextcolor

app:tabTextColor="#000000"
app:tabSelectedTextColor="@color/colorAccent"

but all i want to do now is to change the background color of that specific tab when it is selected ? How to do that ? Thanks in advance :)

Goku
  • 9,102
  • 8
  • 50
  • 81
Nabeel Nazir
  • 420
  • 5
  • 15

2 Answers2

10

you can do it like this in your tab layout widget

<android.support.design.widget.TabLayout

    app:tabBackground="@drawable/selector"

    />

and define your selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
     android:drawable="@color/tab_selected_color" 
     android:state_selected="true"/>
    <item 
     android:drawable="@color/tab_unselected_color"
     android:state_selected="false"/>
</selector>
sunil kushwah
  • 495
  • 1
  • 6
  • 20
3

Change the background colour of tab in TabLayout is fairly simple using the design support library that Android provides. You can simply change the background of the whole TabLayout using the app:tabBackground property and you can change the tab indicator colour using the app:tabIndicatorColor property, but there are better ways if you want more functionality. A better way to change the tab-layout colour is using selectors, using selectors you can have different background for different sates of tab i.e selected, unselected etc.

Please follow the below steps:

1. Create a drawable, tab_selected_background, that will be use as the background for the selected tab

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary" />
    <corners android:radius="4dp" />
</shape>

2. Create a selector, tab_selector that will be used as the background for tab layout:

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

3. Now finally create the tab layout and use the selector that we've just create as the background of the tabLayout.

  <android.support.design.widget.TabLayout
        android:id="@+id/subChordTabs"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:tabGravity="center"
        app:tabMode="scrollable"
        app:tabBackground="@drawable/tab_selector"
        app:tabIndicatorColor="@color/tabIndicator"
        android:padding="8dp"
        app:tabIndicatorHeight="2dp"/>

You gotta the result like below,

enter image description here

Fenil Patel
  • 1,528
  • 11
  • 28