Learn Android Development
Demystify Jetpack Compose Layout Constraint and Size Setting
Mastering one of the most confusing Jetpack Compose APIs I encountered
Published in
11 min readJun 27, 2023
I shared about how one can support negative padding in Jetpack Compose. The best solution used is to use Jetpack Compose Custom Layout Modifier.
However, although the code seems clear, the logic behind how that happened is most confusing for me.
Take for example the below divider, where we change the layout width
@Composable
private fun DividerLayoutWidthChanged(layoutWidth: Int) {
Divider(modifier = Modifier
.height(20.dp)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(
width = layoutWidth.dp.roundToPx(),
height = placeable.height
) { placeable.place(0, 0) }
}
)
}
As we modify the width, we thought the divider’s length would change. But it didn’t. Instead, confusingly 😕
- It just got moved around, like placement functionality.
- And sometimes, no visual different change as we change the width size.