如果 Android 设备处于暗模式,我如何以编程方式检测?
How can I detect programmatically if the Android Device is in Dark Mode?
我正在尝试为我的 Android 应用程序支持 Android Q Dark 主题,但我不知道如何根据我当前使用的主题导入不同的资产。
我使用官方 DayNight 主题来制作 dark/light 版本,对于可绘制对象,只需指向 XML 即可,它会从 values 或 values-night 中选择正确的值取决于启用的内容。
我想做一些类似的事情,根据主题它会加载资产 "priceTag_light.png" 或 "priceTag_dark.png"。
val inputStream = if(darkIsEnabled) {
assets.open("priceTag_dark.png")
} else {
assets.open("priceTag_light.png")
}
我有办法得到那个标志吗?
您首先需要在清单中进行此更改
<activity
android:name=".MyActivity"
android:configChanges="uiMode" />
然后 activity
的 onConfigurationChanged
val currentNightMode = resources.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
}
好的,终于找到了我正在寻找的解决方案。正如 @deepak-s-gavkar points out the parameter that gives us that information is on the Configuration. So, after a small search I found this 文章中给出的示例方法完美地满足了我的需求:
fun isDarkTheme(activity: Activity): Boolean {
return activity.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
使用以下代码:
boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
我正在尝试为我的 Android 应用程序支持 Android Q Dark 主题,但我不知道如何根据我当前使用的主题导入不同的资产。
我使用官方 DayNight 主题来制作 dark/light 版本,对于可绘制对象,只需指向 XML 即可,它会从 values 或 values-night 中选择正确的值取决于启用的内容。
我想做一些类似的事情,根据主题它会加载资产 "priceTag_light.png" 或 "priceTag_dark.png"。
val inputStream = if(darkIsEnabled) {
assets.open("priceTag_dark.png")
} else {
assets.open("priceTag_light.png")
}
我有办法得到那个标志吗?
您首先需要在清单中进行此更改
<activity
android:name=".MyActivity"
android:configChanges="uiMode" />
然后 activity
的 onConfigurationChangedval currentNightMode = resources.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
}
好的,终于找到了我正在寻找的解决方案。正如 @deepak-s-gavkar points out the parameter that gives us that information is on the Configuration. So, after a small search I found this 文章中给出的示例方法完美地满足了我的需求:
fun isDarkTheme(activity: Activity): Boolean {
return activity.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
使用以下代码:
boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;