Search code examples
androidxmlandroid-tabs

How to change color of tab selected in tablayout


How do I change the color of the selected tab? I would like to each tab to have its own color attribute. So tab 1 selected would be Red. Tab 2 selected would be Blue. Tab 3 selected is Yellow. When not selected they go back to the tab original color.

Currently, I am using a selector to change the background of the selected tab. However, that only allows for one color. I would like to have multiple colors

This is the unselected_tab.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid
        android:color="@color/colorPrimaryDark" />

</shape>

This is the selected_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid
        android:color="@color/tabSelectedColor" />

</shape>

This is the selector I am using

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="50"
    android:exitFadeDuration="50" >

    <item android:drawable="@drawable/tab_selected"
        android:state_selected="false" />
    <item android:drawable="@drawable/tab_unselected"
        android:state_selected="true"/>
</selector>

And I am applying it to the tablayout background

<com.google.android.material.tabs.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimaryDark"
            android:minHeight="?attr/actionBarSize"
            android:elevation="5dp"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:tabIndicatorColor="@android:color/white"
            app:tabMode="scrollable"
            app:tabMaxWidth="100dp"
            app:tabBackground="@drawable/tab_selector"
            />

Below here are some screen shots of how it looks currently. enter image description here

enter image description here

Ideally, I would like for each tab to have its own separate color.

How can accomplish this?

EDIT: IDEALLY I WOULD LIKE TO CHANGE EACH TAB COLOR PROGRAMATICALLY


Solution

  • For anyone who is looking for a solution to this. I was able to find one. You can apply the color to the layout of the child of the tabLayout. For some reference code this is what I used a worked really well for me

    final LinearLayout tabsContainerLayout = (LinearLayout)expenseTabs.getChildAt(0);
    Linear LayouttempLinearLayout = (LinearLayout)tabsContainerLayout.getChildAt(selectedTabPosition);
    tempLinearLayout.setBackgroundColor(Color.RED);