Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the app:tabBackground of a tabLayout programmatically?

Tags:

android

This is my code: It's a tabLayout that I setupWith a Viewpager

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-light"
        app:tabPaddingEnd="-1dp"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabPaddingStart="-1dp"
        app:tabTextAppearance="@style/MineCustomTabText" />

But how do I set this programmatically?

 app:tabBackground="@drawable/tab_color_selector"

It is really important to set this tabBackground programmatically because I want the color to change depending on the theme that the user has chose

These are what I've already tried but none of them is working:

    tabLayout.setBackground(getResources().getDrawable(R.drawable.tab_color_selector));
    tabLayout.setBackgroundResource((R.drawable.tab_color_selector));
    tabLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_color_selector));
    tabLayout.setBackground(ContextCompat.getDrawable(this, R.drawable.tab_color_selector));

Note:

This is my tab_color_selector.xml in drawable:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white" android:state_selected="true" />
    <item android:drawable="@color/blue_alu" />
</selector>
like image 772
TSR Avatar asked Mar 01 '17 15:03

TSR


1 Answers

Try this.

ViewGroup tabStrip = (ViewGroup) tabLayout.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
    View tabView = tabStrip.getChildAt(i);
    if (tabView != null) {
        int paddingStart = tabView.getPaddingStart();
        int paddingTop = tabView.getPaddingTop();
        int paddingEnd = tabView.getPaddingEnd();
        int paddingBottom = tabView.getPaddingBottom();
        ViewCompat.setBackground(tabView, AppCompatResources.getDrawable(tabView.getContext(), tabViewBgResId));
        ViewCompat.setPaddingRelative(tabView, paddingStart, paddingTop, paddingEnd, paddingBottom);
    }
}
like image 54
Ankur Avatar answered Sep 28 '22 06:09

Ankur