Modifying the background color and selected color of tab in TabLayout can be done using design support library that Android provides. One can change the background of the whole TabLayout using the app:tabBackground
property and you can change the tab indicator color using the app:tabIndicatorColor
property.
Better way to change the TabLayout color is using selectors, using selectors you can have different background for different sates of tab i.e selected, unselected etc. Below are the steps for the same
- Create
res/drawable/tab_color_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/tab_background_selected" android:state_selected="true"/> <item android:drawable="@color/tab_background_unselected"/> </selector>
- Modify the
TabLayout
to include the above<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity"> <!-- AppBar Layout --> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="fill_parent" android:layout_height="wrap_content"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="fill_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" > </androidx.appcompat.widget.Toolbar> <!-- Tab Layout for creating tabs --> <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="fill_parent" app:tabBackground="@drawable/tab_color_selector" android:layout_height="wrap_content" /> </com.google.android.material.appbar.AppBarLayout> </androidx.coordinatorlayout.widget.CoordinatorLayout>