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

14

144

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

Englacial answered 26/7, 2015 at 18:38 Comment(0)
G
339

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>
Gilbertogilbertson answered 20/10, 2015 at 7:16 Comment(7)
You can also add a color value to that attribute : ie : app:tabBackground:@color/colorAccentKt
Thank you for the solution. However, I lost default ripple effect with it.Cyclist
How can I do this programatically?Creole
@TSR, if you don't need different colors for each tab, you can do tabLayout.setBackgroundColor(colorInt). If you need it for each tab, you can extract the children from your TabLayoutPupil
to improve look and feel, I think we should also add state_pressed: <item android:drawable="@color/tab_background_selected" android:state_pressed="true"/>Guthrun
How to change textColor as well? Can we achieve with same logic?Verbena
How do I set different tab background for specific tabs?Politi
T
21

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>
Teplica answered 17/9, 2015 at 7:42 Comment(2)
and how to implement this?Creole
Add property android:style to your TabLayout in XML.Jocular
P
15

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>
Psalm answered 29/5, 2016 at 17:20 Comment(0)
D
14

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

Dashiell answered 12/8, 2020 at 11:1 Comment(0)
K
7

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"/>
Kollwitz answered 13/1, 2018 at 18:57 Comment(0)
E
6

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

Exhaustless answered 2/12, 2019 at 19:58 Comment(0)
T
5

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.

Tyrus answered 27/7, 2015 at 4:23 Comment(3)
Yes, I've tried that, but tabLayout changes the full tab widget color, and I can't find a method on tabLayout.Tab that only changes the tab color and the other tabs stay with the same color.Englacial
I am not 100% sure what you are after. If you only want to color the body of one tab then you can add a container/view inside that tab, then you should be able to set the container/view background color in the XML like normal, for example the following will set the background to red android:background=FF0000Tyrus
These other questions/answers may help you: #30904638 and https://mcmap.net/q/161138/-tablayout-tab-styleTyrus
D
2

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.

Diactinic answered 14/12, 2018 at 11:57 Comment(2)
This is taking the accent color automatically. How to give it different color without changing the accent color. thanksSolarize
You can use app:tabIndicatorColor @SolarizeDiactinic
A
2

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();
Accepter answered 19/10, 2020 at 8:58 Comment(0)
B
1

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));
            }
        }
    }
Boyar answered 27/3, 2018 at 13:18 Comment(0)
M
0

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"/>'
Mendez answered 24/12, 2018 at 18:11 Comment(0)
P
0

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) {

        }
    });
Purusha answered 23/9, 2021 at 9:58 Comment(0)
C
0

Another fix for some stubborn cases is to set background of TabLayout to shape selector as in this example:

tablayout_bg.xml at /res/drawable

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

fragment_layout.xml

<com.google.android.material.tabs.TabLayout
 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/tablayout_bg"
        app:tabMode="scrollable"
        >
Cocksure answered 28/10, 2023 at 23:5 Comment(0)
C
-3

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

Contrecoup answered 20/6, 2018 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.