【发布时间】:2021-02-17 11:27:37
【问题描述】:
我想为我的 Android 10 及更高版本的应用应用深色模式。
因此,我在启动时编写了以下代码:
int modeNight;
int colorMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (colorMode == Configuration.UI_MODE_NIGHT_YES) {
modeNight = AppCompatDelegate.MODE_NIGHT_YES;
} else {
modeNight = AppCompatDelegate.MODE_NIGHT_NO;
}
AppCompatDelegate.setDefaultNightMode(modeNight);
这通常有效。如果我启动应用程序,就会设置正确的模式。
但是,如果应用程序仍在后台,我将再次启动它,这将不起作用。
如果我在应用程序未完全关闭时启动应用程序,getResources().getConfiguration() 不会得到更新,并且它总是返回旧值,直到我终止应用程序并重新启动它。
如何强制应用重新加载资源配置?或者我还能如何解决这个问题?
更新:
我现在用setTheme(R.style.Theme_ImmoFinder24); 替换了AppCompatDelegate.setDefaultNightMode(modeNight);。
这适用于一般主题,但我仍然有一个问题:
我有一些元素(回收器视图),用户可以在其中设置背景颜色。一种颜色用于正常模式,一种颜色用于深色模式。
主题变了,但是颜色听AppCompatDelegate.setDefaultNightMode(modeNight);中设置的值。
如果我同时保留setDefaultNightMode() 和setTheme(R.style.Theme_ImmoFinder24);,它不会改变任何问题的开始(没有 setTheme())。
【问题讨论】:
标签: android android-10.0 android-dark-theme