How can I detect programmatically if the Android Device is in Dark Mode?

前端 未结 2 741
忘掉有多难
忘掉有多难 2021-02-08 06:21

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

相关标签:
2条回答
  • 2021-02-08 07:08

    You first need to do this changes in manifest

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

    then onConfigurationChanged of activity

    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
    }
    
    0 讨论(0)
  • 2021-02-08 07:14

    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
        }
    
    0 讨论(0)
提交回复
热议问题