Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-compose-list

How can I know the how many items will be drawn on the screen, so I can put a custom item as the last item. Without scrolling. Using Jetpack Compose


I want to show items in a grid but not scrollable. How can I know how many items I will draw on the screen based on its height and width. here i am showing only 9 items on the screen and putting the last custom item, but if I have a bigger screen, I don't know how many items will be drawn. How to solve it.

LazyVerticalGrid(
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        columns = GridCells.Adaptive(120.dp)
    ) {
        if (viewModel.state.value.participantsShown.size > 8) {
            items(viewModel.state.value.participantsShown.subList(0, 8)) {
                Audience(participant = it)
            }
            item {
                OpenAllParticipants(viewModel = viewModel)
            }
        } else {
            items(viewModel.state.value.participantsShown) {
                Audience(participant = it)
            }
            item {
                OpenAllParticipants(viewModel = viewModel)
            }
        

Solution

  • I measured the available width and height and based on it I decided how many items I will draw.

    BoxWithConstraints(contentAlignment = Center) {
                val audienceHeight = 120.dp
                val audienceWidth = 120.dp
                val padd = 8.dp
                val paddH = 32.dp
                val col = maxWidth.div(audienceWidth + padd).toInt()
                val row = maxHeight.div(audienceHeight + paddH).toInt()
                println("Col $col")
                println("Row $row")
                val itemsToDraw = (col * row)
                viewModel.state.value.itemsToDraw = itemsToDraw
    
                LazyVerticalGrid(
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    columns = GridCells.Adaptive(120.dp),
                    modifier = Modifier
                ) {
                    val participantsSize = viewModel.state.value.participantsShown.size
                    items(
                        viewModel.state.value.participantsShown.subList(
                            fromIndex = 0,
                            toIndex = minOf(itemsToDraw - 1, participantsSize)
                        )
                    ) {
                        Audience(participant = it)
                    }
                    item {
                        OpenAllParticipants(viewModel = viewModel)
                    }
                }
            }