如何以编程方式启用夜间模式?

编程入门 行业动态 更新时间:2024-10-26 07:22:50
本文介绍了如何以编程方式启用夜间模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种使用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,然后执行切换到夜间模式.我已经在APIv23(Android 6.0)及更高版本中对其进行了测试,并且工作正常. 有关更好的说明,请参见此代码实验室由Android

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

更多推荐

如何以编程方式启用夜间模式?

本文发布于:2023-05-23 14:44:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:夜间   模式   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!