如何以编程方式启用夜间模式? [英] How to enable night mode programmatically?
问题描述
我正在寻找一种使用Android代码以编程方式启用夜间模式的方法:
I am looking for a way to enable night mode programmatically with an Android code:
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);
}
}
我的屏幕上没有任何变化,夜间模式仍处于禁用状态. 根据此链接
Nothing has changed on my screen, the night mode is still disables. According to this link
无需启用carMode或deskMode. 我在Android Studio上有以下日志记录:
There is no need to enable carMode or deskMode. I have the following logcat on Android Studio:
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
推荐答案
确保在 styles.xml 文件中将默认主题从Theme.AppCompat.Light.DarkActionBar
更改为Theme.AppCompat.DayNight.DarkActionBar
,然后执行
Make sure to change the default theme from Theme.AppCompat.Light.DarkActionBar
to Theme.AppCompat.DayNight.DarkActionBar
in the styles.xml file and then do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
to switch to the night mode. I have tested it in APIv23(Android 6.0) and above and it is working fine.
For a better explanation see this codelab by Android
这篇关于如何以编程方式启用夜间模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!