Izadi Egizabal
Izadi Egizabal

Reputation: 806

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

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?

Upvotes: 23

Views: 14137

Answers (4)

Mori
Mori

Reputation: 4631

In Kotlin I use this way NightMode=33, DayMode=17:

if ( applicationContext.resources.configuration.uiMode==33) 
# do something here
        else 
# do something here

Upvotes: 0

tsik
tsik

Reputation: 629

Use the following code:

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

Upvotes: 8

Deepak S. Gavkar
Deepak S. Gavkar

Reputation: 457

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
}

Upvotes: 7

Izadi Egizabal
Izadi Egizabal

Reputation: 806

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
    }

Upvotes: 31

Related Questions