Skip to content

Instantly share code, notes, and snippets.

@skydoves
Created January 20, 2022 05:27
Show Gist options
  • Save skydoves/b24d3808a594ee33eadd184a46c55a74 to your computer and use it in GitHub Desktop.
Save skydoves/b24d3808a594ee33eadd184a46c55a74 to your computer and use it in GitHub Desktop.
window_compose_remember
/**
* Copyright 2022 Google LLC.
* SPDX-License-Identifier: Apache-2.0
*
* 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)
}
/**
* Remembers the [Size] in pixels of the window corresponding to the current window metrics.
*/
@Composable
private fun Activity.rememberWindowSize(): Size {
val configuration = LocalConfiguration.current
// WindowMetricsCalculator implicitly depends on the configuration through the activity,
// so re-calculate it upon changes.
val windowMetrics = remember(configuration) {
WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(this)
}
return windowMetrics.bounds.toComposeRect().size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment