首页 > 解决方案 > windowbackground 在深色和浅色主题中不起作用

问题描述

我有一个用户可以选择浅色或深色的主题,一切正常,但是有两个问题:

  1. 当我打开应用程序[在深色/浅色主题中]时,首先显示一个白色页面,然后应用程序使用深色主题
  2. 当我更改主题时,首先出现黑屏

我试图改变背景但没有用,我改变了它的颜色,还使用了可绘制的形状。无论如何,它不起作用,两者都使用一种颜色。

样式.xml

 <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar"/>

值/主题.xml

<style name="Theme.MaterialComponents.DayNight.NoActionBar"
        parent="Theme.MaterialComponents.Light.NoActionBar">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@drawable/window_background</item>
</style>

值夜/themes.xml

<style name="Theme.MaterialComponents.DayNight.NoActionBar"
        parent="Theme.MaterialComponents.NoActionBar">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/TabBackground</item>
    <item name="colorAccent">@color/green_inactive</item>
    <item name="android:windowBackground">@drawable/window_background_dark</item>

</style>

windows_background

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#64b5f6"/>
</shape>

windows_background_dark

和上面的代码类似,只是颜色不同

这就是我加载主题的方式

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Prefs.getIsDarkMode(getApplicationContext()))
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    else
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

    setContentView(R.layout.activity_main);
}

标签: javaandroidstyles

解决方案


无需为背景创建单独的文件。您可以在黑暗和夜间 xml 文件本身中执行此操作。查看以下链接。我已通过此视频实现夜间模式。

https://youtu.be/-qsHE3TpJqw 如果您在执行中有任何问题,请留言。


推荐阅读