Home > Blockchain >  Jetpack Compose reversed column
Jetpack Compose reversed column

Time:12-13

I need to create a column with a reversed order, meaning that given the items

Column {
    A
    B
    C
}

It renders:

C
B
A

I see that LazyColumn can do this with the reverseLayout param, but I can't find anything for the regular Column. Has anyone figured out how to do this? I'd rather not have to create a custom layout.

The reason I'm doing this is I'm creating a generic Modal component where the footer buttons switch to a vertical column at small widths. According to our design system, positive actions should go at the top of the column. Generally, this is the last item in the source order, hence my need to reverse the list.

CodePudding user response:

Why don't you just reverse the list before passing it to Column for displaying? As per Kotlin docs, you can do it like this:

fun main() {
val list = (1..5).toList()

val reverse: List<Int> = list.reversed();
println(reverse)
}

I know your question is asking for something else, but I thought this might be helpful.

CodePudding user response:

Since your'e using column, you can simply reverse the backing structure

val items = listOf("Apple", "Banana", "Cherry", "Dogs", "Eggs", "Fruits")

// or
// val items = remember { mutableStateListOf("Apple", "Banana", "Cherry", "Dogs", "Eggs", "Fruits") }


ReversedColumn(items = items.reversed()) // reversed

Sample composable

@Composable
fun ReversedColumn(items: List<String>) {

    Column(
        modifier = Modifier.verticalScroll(rememberScrollState())
    ) {

        items.forEach {
            Box(modifier = Modifier
                .height(80.dp)
                .fillMaxWidth()
                .border(BorderStroke(Dp.Hairline, Color.Gray)),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = it
                )
            }
        }
    }
}
  • Related