如何获取Android系统主题变更的通知?

jda*_*ier 7 java android themes android-intent kotlin

Android 在 API 级别 29 及更高版本中引入了深色主题 ( https://developer.android.com/guide/topics/ui/look-and-feel/darktheme )。要在您自己的应用程序中支持深色主题,您的应用程序的主题需要继承自 DayNight 主题。但是,如果您使用自己的主题,Android 是否有任何意图让您注意到系统主题更改?

Nik*_*lgo 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
}
Run Code Online (Sandbox Code Playgroud)

编辑:由于原始问题并非特定于 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;
}
Run Code Online (Sandbox Code Playgroud)

来源