Android: 如何切换深色模式的主题?
Android: How to switch theme for dark mode?
从Android10开始,您可以在深色模式和默认浅色模式之间切换。由于这是一个新主题,我还没有对此进行更深入的研究。 OS 是否会自动切换深色模式颜色,或者如果打开深色模式,是否有任何方法可以告诉我的应用程序切换不同的应用程序主题?某些 Android 9 设备也可以使用暗模式。
因为我使用自定义参数制作了自定义深色主题,并为资源中的每种颜色设置了深色(使用 attrs.xml
中的自定义属性,并在 [=12= 中的主题内向它们应用了特定的颜色资源]).同样它适用于我的应用程序的不同配色方案(例如蓝色、红色、绿色)。这样我就可以知道我的应用程序而不是系统中的不同视图将使用哪种颜色。
我唯一需要做的就是检测系统中是否 on/off 暗模式。我可以强制用户在应用程序设置(自定义设置)中打开深色模式,但主题可能会受到系统深色模式的影响(在 Phone 设置中打开)。
In order to support Dark theme, you must set your app's theme (usually found in res/values/styles.xml) to inherit from a DayNight theme:
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
You can also use MaterialComponents' dark theming:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
This ties the app's main theme to the system-controlled night mode flags and gives the app a default Dark theme (when it is enabled).
这意味着如果您使用 DayNight 主题,OS 本身会处理应用程序主题。如果您想强制应用使用深色主题,请检查 this 文档。
更新:
检测设备主题:
switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
case Configuration.UI_MODE_NIGHT_YES:
…
break;
case Configuration.UI_MODE_NIGHT_NO:
…
break;
}
从Android10开始,您可以在深色模式和默认浅色模式之间切换。由于这是一个新主题,我还没有对此进行更深入的研究。 OS 是否会自动切换深色模式颜色,或者如果打开深色模式,是否有任何方法可以告诉我的应用程序切换不同的应用程序主题?某些 Android 9 设备也可以使用暗模式。
因为我使用自定义参数制作了自定义深色主题,并为资源中的每种颜色设置了深色(使用 attrs.xml
中的自定义属性,并在 [=12= 中的主题内向它们应用了特定的颜色资源]).同样它适用于我的应用程序的不同配色方案(例如蓝色、红色、绿色)。这样我就可以知道我的应用程序而不是系统中的不同视图将使用哪种颜色。
我唯一需要做的就是检测系统中是否 on/off 暗模式。我可以强制用户在应用程序设置(自定义设置)中打开深色模式,但主题可能会受到系统深色模式的影响(在 Phone 设置中打开)。
In order to support Dark theme, you must set your app's theme (usually found in res/values/styles.xml) to inherit from a DayNight theme:
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
You can also use MaterialComponents' dark theming:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
This ties the app's main theme to the system-controlled night mode flags and gives the app a default Dark theme (when it is enabled).
这意味着如果您使用 DayNight 主题,OS 本身会处理应用程序主题。如果您想强制应用使用深色主题,请检查 this 文档。
更新:
检测设备主题:
switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
case Configuration.UI_MODE_NIGHT_YES:
…
break;
case Configuration.UI_MODE_NIGHT_NO:
…
break;
}