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

问题描述 投票:0回答:1

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

我已经尝试过下面的代码行。没工作。还包括我的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"/>

谢谢您的帮助。

background-color android-tablayout
1个回答
0
投票

我通过在onCreate中设置内容视图之前检查我为night主题设置的布尔值来解决它。

@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>

样式文件引用了控制背景颜色的不同drawable,如上所示..这里是drawables ...

这是夜间模式drawable:

<?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>

这是常规模式drawable:

<?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的样式文件。我希望这是有道理的。我测试了它,它对我有用。我尝试了很多其他的东西,没有任何效果。在检查布尔值之前调用共享首选项以获取值非常重要。我希望这可以帮助别人。

© www.soinside.com 2019 - 2024. All rights reserved.