【问题标题】:How can I detect programmatically if the Android Device is in Dark Mode?如何以编程方式检测 Android 设备是否处于暗模式?
【发布时间】:2019-08-28 04:29:41
【问题描述】:

我正在尝试为我的 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")
                  }

有什么方法可以让我得到那个标志吗?

【问题讨论】:

    标签: android kotlin android-theme android-dark-theme


    【解决方案1】:

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

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

    【讨论】:

    • 你也可以用Context代替Activity,这样更容易使用:·)
    • fun Context.isDarkTheme(): Boolean { return resources.configuration.uiMode 和 Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES }
    【解决方案2】:

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

    <activity
        android:name=".MyActivity"
        android:configChanges="uiMode" />
    

    然后活动的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
    }
    

    【讨论】:

    • 他想知道是否启用了暗模式,这是 Android Q 的功能。
    • 这不是我想要的,因为我想在开始时检查,而不是在产生更改时检查。但它为我指明了正确的方向并找到了我正在寻找的东西。谢谢!
    • 为什么需要将uiMode设置为configChanges?
    【解决方案3】:

    使用以下代码:

    boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)  == Configuration.UI_MODE_NIGHT_YES;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多