java - windowbackground 在深色和浅色主题中不起作用
问题描述
我有一个用户可以选择浅色或深色的主题,一切正常,但是有两个问题:
- 当我打开应用程序[在深色/浅色主题中]时,首先显示一个白色页面,然后应用程序使用深色主题
- 当我更改主题时,首先出现黑屏
我试图改变背景但没有用,我改变了它的颜色,还使用了可绘制的形状。无论如何,它不起作用,两者都使用一种颜色。
样式.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);
}
解决方案
无需为背景创建单独的文件。您可以在黑暗和夜间 xml 文件本身中执行此操作。查看以下链接。我已通过此视频实现夜间模式。
https://youtu.be/-qsHE3TpJqw 如果您在执行中有任何问题,请留言。
推荐阅读
- python - 使用正则表达式检查字符串是否包含不包括某些单词的单词组合
- bash - 在模块文件中使用 bash 变量
- java - 引起:gradle intellij插件中的java.lang.UnsupportedClassVersionError
- python - 如何在创建环境时将 .conda 从一个文件夹移动到另一个文件夹
- angular - Ionic Angular - 错误:GooglePlus 类型没有“ɵmod”属性
- c++ - 未定义的行为或优化错误?
- swift - 如何使用与 CoreData/CloudKit 同步的共享
- asp.net - 触摸键盘进入视野时如何保持文本框处于视野中
- node.js - 如何从配置了 ssl 的 nginx 服务的 React 应用程序向 nodejs 后端发送请求
- git - 不是一个一个地 git checkout 文件,而是 checkout 整个提交