-
-
Save skydoves/b24d3808a594ee33eadd184a46c55a74 to your computer and use it in GitHub Desktop.
window_compose_remember
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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