android - 如何设置应用:tabBackground of a tabLayout programmatically?

标签 android

这是我的代码:这是一个 tabLayout,我 setupWith 一个 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" />

但是我该如何以编程方式设置它呢?

 app:tabBackground="@drawable/tab_color_selector"

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

这些是我已经尝试过的方法,但没有一个起作用:

    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:

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

关于android - 如何设置应用:tabBackground of a tabLayout programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535394/

相关文章:

android - R.java 文件实际上做了什么以及如何做

android - 加载 Google map 时的 ProgressBar

android - 使用图层列表自定义背景以显示对角线?

不使用 GCM 的 Android 推送通知

Android YouTubePlayer 制作循环

android - Firemonkey android read_phone_state运行时权限要求获取IMEI

android - 如何获取重力传感器信息?

Android - AQuery 在回调方法上获取图像

android - 小部件自定义图标 Android

android - 将数字字符串格式化为2个十进制 double 字,与数字字符串长度无关