Search code examples
androidandroid-jetpack-composeandroid-jetpacklazycolumn

How to calculate empty space in lazy column after last visible item


How to calculate empty space in lazy column after last visible item in Jetpack compose.

enter image description here


Solution

  • You can use Modifier.onSizeChanged{intSize->} on your LazyColumn and its parent Composble and check the distance between them.

    One thing to note here is it requires another recomposition after getting size of parent and list. So you might need do to a check or refer this answer to get dimensions without recomposition

    How to get exact size without recomposition?

    @Composable
    private fun LazyColumnParentSizeSample() {
    
        var parentHeight by remember { mutableStateOf(0) }
        var listHeight by remember { mutableStateOf(0) }
        Column(modifier=Modifier.fillMaxSize()
            .onSizeChanged {
                parentHeight = it.height
            }) {
    
            LazyColumn(modifier=Modifier.onSizeChanged {
                listHeight = it.height
            }){
                items(10) {
                    Text("Item: $it")
                }
            }
            Text("listHeight: $listHeight, parent height: $parentHeight, difference: ${parentHeight-listHeight}")
    
        }
    }
    

    To get value in dp you can use LocalDensity.current

        val diffInDp = LocalDensity.current.run {(parentHeight-listHeight).toDp()  }