Skip to content

Instantly share code, notes, and snippets.

@bmc08gt
Last active July 22, 2024 14:59
Show Gist options
  • Save bmc08gt/d058ac744e6a9c0617c174de8e176318 to your computer and use it in GitHub Desktop.
Save bmc08gt/d058ac744e6a9c0617c174de8e176318 to your computer and use it in GitHub Desktop.
reversible Column layout
@Composable
public fun Column(
modifier: Modifier = Modifier,
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
content: @Composable () -> Unit
) {
SubcomposeLayout(modifier) { constraints ->
val density = Density(density)
val measurables = subcompose(Unit, content)
val placeables = measurables.map { it.measure(constraints) }
val items = if (reverseLayout) placeables.reversed() else placeables
val totalHeight = items.sumOf { it.height }
val positions = IntArray(items.size)
val sizes = IntArray(items.size) { index ->
items[index].height
}
with (verticalArrangement) {
density.arrange(
totalSize = constraints.maxHeight,
sizes = sizes,
outPositions = positions
)
}
layout(constraints.maxWidth, totalHeight) {
placeables.forEachIndexed { index, placeable ->
placeable.placeRelative(
x = horizontalAlignment.align(
size = placeable.width,
space = constraints.maxWidth,
layoutDirection = layoutDirection
),
y = positions[index]
)
}
}
}
}
@Preview(showBackground = true)
@Composable
private fun Reverse_Column_Preview() {
val data = (0..100)
Row(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
data.onEach {
Text(text = "#$it")
}
}
Column(
modifier = Modifier.weight(1f),
reverseLayout = true,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
data.onEach {
Text(text = "#$it")
}
}
}
}
@bmc08gt
Copy link
Author

bmc08gt commented Jul 21, 2024

Screenshot 2024-07-21 at 12 21 27 PM

Doesn't support full ColumnScope (e.g weight and align) yet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment