如何以编程方式检测 Android 设备是否处于暗模式? [英] How can I detect programmatically if the Android Device is in Dark Mode?

查看:71
本文介绍了如何以编程方式检测 Android 设备是否处于暗模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 Android 应用支持 Android Q Dark 主题,但我不知道如何根据我当前所在的主题导入不同的资产.

我使用官方 DayNight 主题来制作深色/浅色版本和可绘制对象,只需指向 XML 就很容易了,它会根据启用的内容从 values 或 values-night 中选择正确的值.

我想做一些类似的事情,根据主题,它会加载资产priceTag_light.png"或priceTag_dark.png".

val inputStream = if(darkIsEnabled) {assets.open("priceTag_dark.png")} 别的 {assets.open("priceTag_light.png")}

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

解决方案

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

fun isDarkTheme(activity: Activity): Boolean {返回 activity.resources.configuration.uiMode 和Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES}

I'm trying to support the Android Q Dark theme for my Android app and I can't figure out how to import different assets based on the theme I'm currently in.

Im using the official DayNight theme for making the dark/light versions and for drawables is very easy to just point to the XML and it will choose the correct value either from values or values-night depending on what is enabled.

I wanted to do something similar where depending on the theme it would load either the asset "priceTag_light.png" or "priceTag_dark.png".

val inputStream = if(darkIsEnabled) { 
                    assets.open("priceTag_dark.png")
                  } else {
                    assets.open("priceTag_light.png")
                  }

Is there a way I get that flag?

解决方案

Okay finally found the solution I was looking for. As @deepak-s-gavkar points out the parameter that gives us that information is on the Configuration. So, after a small search I found this article that gives this example method that has worked perfectly for what I wanted:

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

这篇关于如何以编程方式检测 Android 设备是否处于暗模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆