Composable Function
Common
@ExperimentalMediaQueryApi
@Composable
@ReadOnlyComposable
fun mediaQuery(query: UiMediaScope.() -> Boolean): Boolean
Evaluates a boolean query against the current UiMediaScope.
Avoid reading properties marked with @FrequentlyChangingValue (such as UiMediaScope.windowWidth or UiMediaScope.windowHeight) inside the query block. Reading these properties will cause the composable to recompose on every frame during events such as window resizing, which can affect the performance.
For queries involving such frequently changing values, use derivedMediaQuery instead.
Parameters
| query | The condition to evaluate against the UiMediaScope. |
Returns
| The boolean result of the query. |
Code Examples
AdaptiveButtonSample
@Composable
fun AdaptiveButtonSample() {
Column(Modifier.padding(top = 100.dp).padding(16.dp)) {
val isTouchPrimary = mediaQuery { pointerPrecision == PointerPrecision.Coarse }
val isUnreachable = mediaQuery { viewingDistance != ViewingDistance.Near }
// Adjust button size for touch targets
val adaptiveSize =
when {
isUnreachable -> DpSize(150.dp, 70.dp)
isTouchPrimary -> DpSize(120.dp, 50.dp)
else -> DpSize(100.dp, 40.dp)
}
// Adjust style for reachability
val label = "Submit"
val adaptiveLabel = if (isUnreachable) label.uppercase(getDefault()) else label
Button(
modifier =
Modifier.clip(RoundedCornerShape(8.dp)).size(adaptiveSize).background(Color.Blue),
onClick = {},
) {
Text(text = adaptiveLabel, color = Color.White, style = TextStyle())
}
}
}
FoldableAwareSample
@Composable
fun FoldableAwareSample() {
Column(Modifier.fillMaxSize()) {
when {
mediaQuery { windowPosture == Posture.Tabletop } -> {
// Tabletop mode layout: Two rows separated by hinge
Column(Modifier.fillMaxSize()) {
Box(
Modifier.weight(1f).background(Color.Red).fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
Text("Tabletop mode")
}
Box(
Modifier.height(20.dp).background(Color.Black).fillMaxWidth()
) // Hinge visualization
Box(Modifier.weight(1f).background(Color.Blue).fillMaxWidth())
}
}
mediaQuery { windowPosture == Posture.Book } -> {
// Book mode layout: Two columns separated by hinge
Row(Modifier.fillMaxSize()) {
Box(
Modifier.weight(1f).background(Color.Red).fillMaxHeight(),
contentAlignment = Alignment.Center,
) {
Text("Book mode")
}
Box(
Modifier.width(20.dp).background(Color.Black).fillMaxHeight()
) // Hinge visualization
Box(Modifier.weight(1f).background(Color.Blue).fillMaxHeight())
}
}
else -> {
// Flat mode
Box(
Modifier.background(Color.LightGray).fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Text("Flat mode")
}
}
}
}
}