首页 > 解决方案 > 如何检测系统是否使用暗模式?

问题描述

我正在使用这个简单的功能来获得暗模式。我在共享首选项中存储了一个布尔值。如果值不存在,我默认返回 false。

这是我的简单代码:

public static boolean getNightMode(){
        SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);
        return pref.getBoolean("nightMode",false);
    }

现在,我不想默认返回 false,而是想返回系统暗模式状态。

我的意思是如果系统使用暗模式,则返回 true。

我怎样才能做到这一点?

标签: androidandroid-theme

解决方案


您可以使用配置设置。

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
}

推荐阅读