androidkotlinandroid-jetpack-composeandroid-jetpack

How to fill the remaining space in LazyColumn Jetpack Compose?


I have a LazyColumn that contains 3 items:

LazyColumn(
    modifier = Modifier.fillMaxSize()
) {
    item {
        Text("Some text..."}
        Text("Some text..."}
    }
    item {
        Spacer(
            modifier = Modifier.weight(1f)
        )
        Text("Copyright © Max 2024")
    }
}

My aim is to place the "Copyright..." text at the bottom of the screen. The problem is that I cannot use a Spacer with Modifier.weight(1f). How can I solve this problem without using a Column?


Solution

  • You can use your custom Arrangment for this that places last item to bottom.

    Result

    enter image description here

    Code

    val ArrangementLazyColumnLastItemToBottom = object : Arrangement.Vertical {
        override fun Density.arrange(totalSize: Int, sizes: IntArray, outPositions: IntArray) {
            var consumedHeight = 0
            sizes.forEachIndexed { index, height ->
                if (index == sizes.lastIndex) {
                    // If it's last item position at the bottom
                    outPositions[index] = totalSize - height
                } else {
                    // If not last item position below other
                    outPositions[index] = consumedHeight
                    consumedHeight += height
                }
            }
        }
    }
    
    @Preview
    @Composable
    fun LazyColumnArrangmentTest() {
    
        LazyColumn(
            modifier = Modifier.fillMaxSize().border(2.dp, Color.Red),
            verticalArrangement = ArrangementLazyColumnLastItemToBottom
        ) {
            item {
                Text("Text1")
            }
            item {
                Text("Text2")
            }
    
            item {
                Text("Text3")
            }
    
            item {
                Text("Text4")
            }
            item {
                Text("Text5")
            }
    
            item {
                Text("Footer")
            }
        }
    }