如何以编程方式设置tabLayout的app:tabBackground? [英] How to set the app:tabBackground of a tabLayout programmatically?

查看:681
本文介绍了如何以编程方式设置tabLayout的app:tabBackground?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:这是我setupWithViewpager

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"

以编程方式设置此tabBackground真的很重要,因为我希望颜色根据用户选择的主题而改变

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

注意:

这是我在drawable中的tab_color_selector.xml:

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>

推荐答案

尝试一下.

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

这篇关于如何以编程方式设置tabLayout的app:tabBackground?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆