android - 如何检测系统是否使用暗模式?
问题描述
我正在使用这个简单的功能来获得暗模式。我在共享首选项中存储了一个布尔值。如果值不存在,我默认返回 false。
这是我的简单代码:
public static boolean getNightMode(){
SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);
return pref.getBoolean("nightMode",false);
}
现在,我不想默认返回 false,而是想返回系统暗模式状态。
我的意思是如果系统使用暗模式,则返回 true。
我怎样才能做到这一点?
解决方案
您可以使用配置设置。
int currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO:
// Night mode is not active, we're using the light theme
break;
case Configuration.UI_MODE_NIGHT_YES:
// Night mode is active, we're using dark theme
break;
}
更多详情,请参考开发者网站。
科特林:
val currentNightMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
when (currentNightMode) {
Configuration.UI_MODE_NIGHT_NO -> {} // Night mode is not active, we're using the light theme
Configuration.UI_MODE_NIGHT_YES -> {} // Night mode is active, we're using dark theme
}
推荐阅读
- sql - 如何查询实体的时间顺序?
- powershell - ForEach-Object 循环似乎不会循环遍历数组项
- java - 在子元素(QName)上解组 jaxb 失败
- android - Firebase DebugView 未在 Android 上显示事件
- excel - 如何编写从范围中提取数值的宏,执行不同的操作,如求和和乘法
- java - 如何沿 Websocket 端点实现 Rest 端点
- java - 应用程序已构建,但在按下按钮时崩溃
- yocto - Bitbake(例如 Yocto)在步骤中挂起:解析食谱
- c# - C# - 从 Azure AD 获取组信息
- c# - 所有方法均以 POSTMAN 形式工作,仅从 SPA 获取