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 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?

Izadi Egizabal
  • 747
  • 1
  • 7
  • 17

3 Answers3

28

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
    }
Izadi Egizabal
  • 747
  • 1
  • 7
  • 17
  • 2
    You can also use `Context` instead of `Activity` to make it easier to use :·) – Roc Boronat Feb 17 '20 at 10:45
  • 4
    fun Context.isDarkTheme(): Boolean { return resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES } – Frank Mar 30 '20 at 12:33
7

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
}
Najib.Nj
  • 3,706
  • 1
  • 25
  • 39
Deepak S. Gavkar
  • 447
  • 8
  • 21
6

Use the following code:

boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)  == Configuration.UI_MODE_NIGHT_YES;
tsik
  • 609
  • 8
  • 10