如何以编程方式检测 Android 设备是否处于暗模式?

Iza*_*bal 17 android android-theme kotlin android-dark-theme

我正在尝试为我的 Android 应用程序支持 Android Q Dark 主题,但我无法弄清楚如何根据我当前所在的主题导入不同的资产。

我使用官方的 DayNight 主题来制作深色/浅色版本和可绘制对象,只需指向 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")
                  }
Run Code Online (Sandbox Code Playgroud)

有没有办法让我得到那个标志?

Iza*_*bal 20

好的,终于找到了我正在寻找的解决方案。正如@deepak-s-gavkar指出的那样,为我们提供信息的参数是关于配置的。因此,经过一番小搜索,我发现这篇文章给出了这个示例方法,它非常适合我想要的:

fun isDarkTheme(activity: Activity): Boolean {
        return activity.resources.configuration.uiMode and
                Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
    }
Run Code Online (Sandbox Code Playgroud)

  • fun Context.isDarkTheme(): Boolean { return resources.configuration.uiMode 和 Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES } (3认同)
  • 您还可以使用“Context”代替“Activity”,以使其更易于使用:·) (2认同)

小智 6

使用以下代码:

boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)  == Configuration.UI_MODE_NIGHT_YES;
Run Code Online (Sandbox Code Playgroud)


Dee*_*kar 5

您首先需要在清单中进行此更改

<activity
    android:name=".MyActivity"
    android:configChanges="uiMode" />
Run Code Online (Sandbox Code Playgroud)

然后 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
}
Run Code Online (Sandbox Code Playgroud)