如何获得有关Android系统主题更改的通知



Android在API 29级及更高版本中引入了黑暗主题(https://developer.android.com/guide/topics/ui/look-and-feel/darktheme)。要在您自己的应用程序中支持黑暗主题,您的应用程序的主题需要继承自DayNight主题。但是,如果你自己做了主题化,安卓是否有意引起人们对系统主题变化的注意?

如果将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;
}

(来源(

最新更新