Android - 如何动态改变背景颜色或整个TabLayout?

Android - How to change the background color or the entire TabLayout dynamically?

我需要通过应用程序中的代码动态更改整个选项卡布局的背景颜色。我只需要知道要输入的正确行。我不需要更改选定的选项卡或任何内容。我想保持样式和文本颜色以及指示线不变。我只想在代码中动态更改整个选项卡布局的背景。感谢您的帮助。

我已经尝试过下面的代码行。没用。还包括我的 TabLayout XML.

private TabLayout mTabLayout;
mTabLayout = (TabLayout) findViewById(R.id.tabs);

mTabLayout.setBackgroundColor
(this.getResources().getColor(R.color.dark_grey));

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/CategoryTab"
        android:layout_width="match_parent"
        android:layout_height="@dimen/activity_generic_margin_28"
        app:tabBackground="@color/app_bar"/>

感谢您的帮助。

我通过在 onCreate 中设置内容视图之前检查我为夜间主题设置的布尔值解决了这个问题。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences nightModeSwitchState = getSharedPreferences("NightModeSwitchState", 0);
    mNightModeSwitchState = nightModeSwitchState.getBoolean("NightModeSwitchState", false);

    if (mNightModeSwitchState) {
        setContentView(R.layout.activity_book_night);
    } else {
        setContentView(R.layout.activity_book);
    }

我有两个布局都包含 tabLayouts。其中之一引用了 tabLayout 的样式文件设置为深色背景的夜间模式颜色,布局引用了设置为 tablayout 常规颜色的样式文件。

<style name="CategoryTab" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">@android:color/white</item>
    <item name="tabSelectedTextColor">@android:color/white</item>
    <item name="tabTextAppearance">@style/CategoryTabTextAppearance</item>
    <item name="tabBackground">@drawable/tab_regular_theme</item>
    <item name="android:textColorSecondary">@android:color/white</item>
</style>

<style name="CategoryTabNight" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">@android:color/white</item>
    <item name="tabSelectedTextColor">@android:color/white</item>
    <item name="tabTextAppearance">@style/CategoryTabTextAppearance</item>
    <item name="tabBackground">@drawable/tab_layout_dark_mode</item>
    <item name="android:textColorSecondary">@android:color/white</item>
</style>

如上所示,样式文件引用了控制背景颜色的不同可绘制对象。这里是可绘制对象...

这是夜间模式的可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/dark_grey" android:state_selected="true"/>
<item android:drawable="@color/dark_grey"/>
</selector>

这是常规模式可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/app_bar" android:state_selected="true"/>
<item android:drawable="@color/app_bar"/>
</selector>

其他一切都是相同的布局,不会弄乱任何东西,只是更改了 tablayouts 的样式文件。我希望这是有道理的。我测试了它,它对我有用。我尝试了很多其他的东西,但没有任何效果。在检查布尔值之前调用 Shared Preference 获取值很重要。我希望这对某人有所帮助。