Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...