简体   繁体   English

windowbackground 不适用于深色和浅色主题

[英]windowbackground not work in dark and light theme

I have a theme that user can choose light or dark, everything work fine but, there are 2 problems:我有一个主题,用户可以选择浅色或深色,一切正常,但是有两个问题:

  1. When I open the app [in dark/light theme ], a white page is displayed first, then the application uses a dark theme当我打开应用程序时[在深色/浅色主题中],首先显示一个白页,然后应用程序使用深色主题
  2. When I change the theme, a black screen appears first当我更改主题时,首先出现黑屏

I tried to change the background but did not work, I changed the color of it and also I used drawable shape.我试图改变背景但没有用,我改变了它的颜色,我还使用了可绘制的形状。 Anyway, it not work and use one color for both.无论如何,它不起作用并且对两者都使用一种颜色。

style.xml样式文件

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

values/themes.xml值/themes.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>

values-night/themes.xml值夜/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 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 windows_background_dark

Similar to the above code, only the color is different和上面的代码类似,只是颜色不同

and this is how I load theme这就是我加载主题的方式

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

There is no need to create seperate file for background.You can do that in the dark and night xml files itself.check out the below link.I have implemented night mode through this video.无需为背景创建单独的文件。您可以在黑暗和夜间 xml 文件中自行完成。请查看以下链接。我已通过此视频实现了夜间模式。

https://youtu.be/-qsHE3TpJqw If you have any problem in implementation,drop a message. https://youtu.be/-qsHE3TpJqw如果您在实施过程中遇到任何问题,请留言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM