我正在寻找一种使用 Android 代码以编程方式启用夜间模式的方法:
public static void setNightMode(Context target, boolean state){
UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);
if (state) {
//uiManager.enableCarMode(0);
uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
} else {
// uiManager.disableCarMode(0);
uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
}
}
我的屏幕上没有任何变化,夜间模式仍处于禁用状态。 根据这个link
无需启用 carMode 或 deskMode。 我在 Android Studio 上有以下 logcat:
11-26 12:15:16.662 3823-3823/? D/UiModeManager: updateConfigurationLocked: mDockState=0; mCarMode=false; mNightMode=2; uiMode=33
11-26 12:15:26.802 3823-3823/? V/UiModeManager: updateLocked: null action, mDockState=0, category=null
最佳答案
最简单的解决方案
您可以通过以下方式启用/禁用应用程序的深色主题:
启用深色主题:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
强制禁用深色主题:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
根据暗模式的移动设置设置应用主题,即如果启用暗模式,则主题将设置为暗主题,否则 默认主题,但这仅适用于version >= Android version Q (10)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
注意事项:
- 您的应用/Activity 的基本主题应该是
"Theme.AppCompat.DayNight"
喜欢
<style name="DarkTheme" parent="Theme.AppCompat.DayNight">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
- 您的 res 文件夹的名称将以 -night 结尾,这样您就可以为日夜主题设置不同的颜色和图像,例如
drawable & drawable-night,
值(value)观与值(value)观之夜
关于android - 如何以编程方式启用夜间模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495534/