如何获取关于Android系统主题更改的通知?

7

Android在API 29及更高版本中引入了暗黑主题(https://developer.android.com/guide/topics/ui/look-and-feel/darktheme)。为了在您自己的应用程序中支持暗黑主题,您的应用程序主题需要继承DayNight主题。 但是如果您进行了自定义主题,那么是否有来自Android的意图来通知您系统主题的更改呢?

1个回答

13

如果您在清单文件中的活动中添加 android:configChanges="uiMode",当用户更改主题时,将调用onConfigurationChanged方法。如果您覆盖它,您可以在其中完成所有相关工作。为了检查当前主题是什么,您可以执行以下操作:

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
}

编辑:由于原始问题不是特定于Kotlin的,因此这里提供上述Java版本以供参考:

int currentNightMode = configuration.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;
}

(源代码)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接