Skip to content

Instantly share code, notes, and snippets.

@alexvanyo
Last active February 3, 2022 10:32
Show Gist options
  • Save alexvanyo/7ae628505a41bd2087273762811c78a9 to your computer and use it in GitHub Desktop.
Save alexvanyo/7ae628505a41bd2087273762811c78a9 to your computer and use it in GitHub Desktop.
Composable method for observing the current window size class
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
enum class WindowSize { Compact, Medium, Expanded }
/**
* Remembers the [WindowSize] class for the window corresponding to the
* current window metrics.
*/
@Composable
fun Activity.rememberWindowSizeClass(): WindowSize {
// Get the size (in pixels) of the window
val windowSize = rememberWindowSize()
// Convert the window size to [Dp]
val windowDpSize = with(LocalDensity.current) {
windowSize.toDpSize()
}
// Calculate the window size class
return getWindowSizeClass(windowDpSize)
}
/**
* Partitions a [DpSize] into an enumerated [WindowSize] class.
*/
fun getWindowSizeClass(windowDpSize: DpSize): WindowSize = when {
windowDpSize.width < 0.dp ->
throw IllegalArgumentException("Dp value cannot be negative")
windowDpSize.width < 600.dp -> WindowSize.Compact
windowDpSize.width < 840.dp -> WindowSize.Medium
else -> WindowSize.Expanded
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment