Function

mediaQuery

Evaluates a query against the current UiMediaScope from a CompositionLocalAccessorScope.

AdaptiveStylesSample

@OptIn(ExperimentalFoundationStyleApi::class)
@Sampled
@Composable
fun AdaptiveStylesSample() {
    // Create a styleable clickable box

MediaQueryModifierNodeSample

@Sampled
@Composable
fun MediaQueryModifierNodeSample() {
    // Example of a custom padding modifier that uses [mediaQuery] within a [Modifier.Node].
    class AdaptivePaddingNode :
        Modifier.Node(), LayoutModifierNode, CompositionLocalConsumerModifierNode {
        override fun MeasureScope.measure(
            measurable: Measurable,
            constraints: Constraints,
        ): MeasureResult {
            val isLargeScreen = mediaQuery { windowWidth > 600.dp && windowHeight > 400.dp }

            // Adjust padding or size based on the query result
            val extraPadding = if (isLargeScreen) 80.dp.roundToPx() else 16.dp.roundToPx()
            val totalPaddingOnAxis = 2 * extraPadding

            // Measure the content with added padding
            val placeable =
                measurable.measure(constraints.offset(-totalPaddingOnAxis, -totalPaddingOnAxis))

            val width = constraints.constrainWidth(placeable.width + totalPaddingOnAxis)
            val height = constraints.constrainHeight(placeable.height + totalPaddingOnAxis)

            return layout(width, height) { placeable.place(extraPadding, extraPadding) }
        }
    }

    class AdaptivePaddingElement : ModifierNodeElement<AdaptivePaddingNode>() {
        override fun create() = AdaptivePaddingNode()

        override fun update(node: AdaptivePaddingNode) {}

        override fun equals(other: Any?) = other === this

        override fun hashCode() = 0
    }
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: