How do I change a tab background color when using TabLayout?

AndroidAndroid TabsAndroid Tablayout

Android Problem Overview


This is my code in the main activity

public class FilterActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_filter);

    // Get the ViewPager and set it's PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), FilterActivity.this);
    viewPager.setAdapter(pageAdapter);

    // Give the TabLayout the ViewPager
    final TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);



  }
}

And this is my code in the XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar">
    </include>

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="fill_parent"
        style="@style/MyCustomTabLayout"
        android:layout_height="48dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>

I want to change the background color of one tab when it's selected

Android Solutions


Solution 1 - Android

What finally worked for me is similar to what @如果我是DJ suggested, but the tabBackground should be in the layout file and not inside the style, so it looks like:

res/layout/somefile.xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

and the selector 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>

Solution 2 - Android

You can try this:

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabBackground">@drawable/background</item>
</style>

In your background xml file:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/white" />
    <item android:drawable="@color/black" />
</selector>

Solution 3 - Android

Add atribute in xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

And create in drawable folder, 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>

Solution 4 - Android

You can have it in the xml.

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextColor="@color/colorGray"
        app:tabSelectedTextColor="@color/colorWhite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Solution 5 - Android

After some messing around this is how I got the desired look (at least in the emulator) and it keeps the ripple effect.

tab layout with tab selector with color argument

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_selector"
    app:tabIconTint="@drawable/tab_selector"
    app:tabIconTintMode="src_atop"
    app:tabTextColor="@drawable/tab_selector" />

And the @drawable/tab_selector:

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

FYI: This is what the emulator showed before I added the color argument to @drawable/tab_selector:

tab layout with tab selector without color argument

Solution 6 - Android

One of the ways I could find is using the tab indicator like this:

<com.google.android.material.tabs.TabLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/normal_unselected_color"
    app:tabIndicatorColor="@color/selected_color"
    app:tabIndicatorGravity="center"
    app:tabIndicatorHeight="150dp"
    app:tabSelectedTextColor="@color/selected_text_color"
    app:tabTextColor="@color/unselected_text_color">

    ..... tab items here .....

</com.google.android.material.tabs.TabLayout>

Trick is to:

  • Make the tab indicator to align in center
  • Make the indicator height sufficiently large so that it covers the whole tab

This also takes care of the smooth animation while switching tabs

Solution 7 - Android

Have you tried checking the API?

You will need to create a listener for the OnTabSelectedListener event, then when a user selects any tab you should check if it is the correct one, then change the background color using tabLayout.setBackgroundColor(int color), or if it is not the correct tab make sure you change back to the normal color again with the same method.

Solution 8 - Android

As I found best and suitable option for me and it will work with animation too.

You can use indicator it self as a background.

You can set app:tabIndicatorGravity="stretch" attribute to use as background.

Example:

   <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorGravity="stretch"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/colorAccent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chef" />


        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User" />

    </android.support.design.widget.TabLayout>

Hope it will helps you.

Solution 9 - Android

Since ViewPager is tending to be replaced by ViewPager2 and we will need to migrate to it.

A quick work around using Java would be something like this:

    final List<String> colors = new ArrayList<String>(){
        {
            add("#FF0000");
            add("#800000");
            add("#FFFF00");
        }
    };

    
    ViewPager2 viewPager = findViewById(R.id.viewPager);
    ViewPagerAdapter adapter = new ViewPagerAdapter(your_data_structure);
    viewPager.setAdapter(adapter);

    final TabLayout tabs = findViewById(R.id.tabs);

    tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tab.view.setAlpha((float) 0.5);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.view.setAlpha(1);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    TabLayoutMediator mediator = new TabLayoutMediator(tabs, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
        @Override
        public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
            tab.setText("Tab" + position);
			
			/* 
			*  With this feature the TabIndicator color is ignored 
			*  or covered by the new color ex.(if alpha channel is changed the indicator can be seen through)
			*/
            tab.view.setBackgroundColor(Color.parseColor(colors.get(position))); //You can use your HEX string color
        }
    });

    mediator.attach();

Solution 10 - Android

You can change the background or ripple color of each Tab like this:

    //set ripple color for each tab
    for(int n = 0; n < mTabLayout.getTabCount(); n++){

        View tab = ((ViewGroup)mTabLayout.getChildAt(0)).getChildAt(n);

        if(tab != null && tab.getBackground() instanceof RippleDrawable){
            RippleDrawable rippleDrawable = (RippleDrawable)tab.getBackground();
            if (rippleDrawable != null) {
                rippleDrawable.setColor(ColorStateList.valueOf(rippleColor));
            }
        }
    }

Solution 11 - Android

You can change the background color of the tab by this attribute

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
'android:background="@color/primary_color"/>'

Solution 12 - Android

You can simply use tab.view.setBackground(drawable) in tabLayout.addOnTabSelectedListener as given below:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tab.view.setBackground(getResources().getDrawable(R.drawable.ic_rectangle_1345));
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.view.setBackgroundColor(Color.TRANSPARENT);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

Solution 13 - Android

One of simplest solution is to change colorPrimary from colors.xml file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoel LaraView Question on Stackoverflow
Solution 1 - AndroidTakoView Answer on Stackoverflow
Solution 2 - Android如果我是DJView Answer on Stackoverflow
Solution 3 - AndroidHai RomView Answer on Stackoverflow
Solution 4 - AndroidXurajBView Answer on Stackoverflow
Solution 5 - AndroidrexxarView Answer on Stackoverflow
Solution 6 - AndroidAnubhab MajiView Answer on Stackoverflow
Solution 7 - AndroidsorifiendView Answer on Stackoverflow
Solution 8 - AndroidPratik ButaniView Answer on Stackoverflow
Solution 9 - Androidgmonster1stView Answer on Stackoverflow
Solution 10 - AndroidJosé MaurícioView Answer on Stackoverflow
Solution 11 - AndroidM_OwaisView Answer on Stackoverflow
Solution 12 - AndroidAli AslamView Answer on Stackoverflow
Solution 13 - AndroidAhmad SadiqView Answer on Stackoverflow