16

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
  • 449
  • 3
  • 15

3 Answers3

19

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
  • 449
  • 3
  • 15
  • 2
    You can also use `Context` instead of `Activity` to make it easier to use :·) – Roc Boronat Feb 17 '20 at 10:45
  • 2
    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
4

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
}
NAP Developer
  • 3,353
  • 1
  • 21
  • 35
Deepak S. Gavkar
  • 397
  • 5
  • 20
0

Use the following code:

boolean isDarkThemeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)  == Configuration.UI_MODE_NIGHT_YES;
tsik
  • 449
  • 4
  • 9