Khantahr
Khantahr

Reputation: 8528

Jetpack Compose Getting Light vs Dark Mode from MaterialTheme Using Material 3

With Jetpack Compose, using Material 2, you can see if a theme is in light mode easily with the following

val light = MaterialTheme.colors.isLight

Using Material 3, I don't see this ability. Is there a way to do this with a Material 3 theme?

Upvotes: 24

Views: 9248

Answers (3)

Mikhail
Mikhail

Reputation: 21

In your Theme.kt file you use LightColorScheme and DarkColorScheme for example. Your background color in this color schemas are different. You can use this function in your Theme.kt file for checking:

@Composable fun isLightTheme() = LightColorScheme.background == MaterialTheme.colorScheme.background

Upvotes: 0

Khantahr
Khantahr

Reputation: 8528

Found a solution. Color in Compose has a built in method luminance that returns the relative luminance as a float between 0 and 1. I wrote an extension function for ColorScheme that returns true if the luminance of the background is greater than 0.5.

@Composable
fun ColorScheme.isLight() = this.background.luminance() > 0.5

Using it as:

val isLight = MaterialTheme.colorScheme.isLight()

Now whether the system is in dark mode doesn't matter, only the theme.

Upvotes: 24

Immanuel Diaz
Immanuel Diaz

Reputation: 402

In JetpackCompose you can use this method that returns if the light / dark mode is enabled or not

isSystemInDarkTheme()

And then in your code

if (isSystemInDarkTheme()){} \\Dark mode enabled
else {} //Light mode enabled 

Upvotes: 19

Related Questions