How to set footer height same as items in LazyRow?

Viewed 39

I have a few a list of items, I want to attach a footer to it. The content of items is different from footer and that is why they have different heights.

LazyRow() {
    items(myList) { item ->
           RowItem(item)
    }
    item {
           Footer()
    }
}

I want the footer to be of the same height as other items.

1 Answers

You can do this by getting height of RowItem using Modifier.onSizeChanged, assuming all of your items have same same height, then after converting height in Int to Dp and set it as height of your Footer

Here is an example with LazyRow

@Composable
private fun DynamicFooterList() {
    var height by remember { mutableStateOf(0.dp) }
    val density = LocalDensity.current

    LazyRow(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(count=5) { item ->
            Card(
                modifier = Modifier.onSizeChanged {
                    if (height == 0.dp) {
                        height = with(density) { it.height.toDp() }
                    }
                }
            ) {
                Column {
                    Image(
                        painter = painterResource(id = R.drawable.landscape5_before),
                        contentDescription = null
                    )
                    Text(
                        modifier = Modifier.padding(8.dp),
                        text = "Image inside Card",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }

        item {
            Box(
                modifier = (if (height > 0.dp) Modifier.height(height) else Modifier).then(
                    Modifier.background(
                        Color.LightGray, CutCornerShape(8.dp)
                    )
                ),
                contentAlignment = Alignment.Center
            ) {
                Text("A liitle long Footer", fontSize = 20.sp)
            }
        }
    }
}

You can use a conditional Modifier for RowItem if you want to not check size after height is 0.dp but don't know if it would have any effect on performance

enter image description here

Related