androidx.compose.ui.layout
SubcomposeLayout
Composable function · from org.jetbrains.compose.ui:ui:1.12.2
A normal Layout gets all its children first, then measures them. SubcomposeLayout can measure some children, and then decide what other children to create, using what it measured.
Scaffold, BoxWithConstraints and the lazy lists are built on it. For example, Scaffold measures the top bar first, then creates the content with the right padding.
SubcomposeLayout { constraints ->
val header = subcompose("header") { Header() }.map { it.measure(constraints) }
val headerHeight = header.sumOf { it.height }
// The body is created only now, and knows how tall the header is.
val body = subcompose("body") { Body(headerHeight) }.map { it.measure(constraints) }
layout(constraints.maxWidth, constraints.maxHeight) {
header.forEach { it.place(0, 0) }
body.forEach { it.place(0, headerHeight) }
}
}
It is slower than a normal layout. Use it only when one child's content really depends on another's size. Often BoxWithConstraints or a custom Layout is enough.
Read more
- Custom layouts (Android Developers)
- Advanced layouts in Compose (Android Developers, video): the layout phase, subcomposition and intrinsic sizes
- SubcomposeLayout reference (Android Developers)
Basic
The usual form.
@Composable
fun SubcomposeLayout(
modifier: Modifier = Modifier,
measurePolicy: SubcomposeMeasureScope.(Constraints) -> MeasureResult,
)
modifier: ModifierOptional
modifier: ModifierOptionalDefault: Modifier
Changes size, padding, or position. See the Modifier guide.
measurePolicy: SubcomposeMeasureScope.(Constraints) -> MeasureResultRequired
measurePolicy: SubcomposeMeasureScope.(Constraints) -> MeasureResultRequiredYour measuring code. Call subcompose(slotId) { ... } to create children, measure them, and end with layout(width, height) { ... }.
With a state
Lets you keep and reuse children between layouts.
@Composable
fun SubcomposeLayout(
state: SubcomposeLayoutState,
modifier: Modifier = Modifier,
measurePolicy: SubcomposeMeasureScope.(Constraints) -> MeasureResult,
)
state: SubcomposeLayoutStateRequired
state: SubcomposeLayoutStateRequiredKeeps children between layouts so they can be reused. Create it with remember { SubcomposeLayoutState() }.
Same as above: modifier, measurePolicy.