Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EmmanuelGuther/17c926ff5a39cf22220a7077767b1397 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/17c926ff5a39cf22220a7077767b1397 to your computer and use it in GitHub Desktop.
Compose Animate Scroll And Centralize Item
fun LazyListState.animateScrollAndCentralizeItem(index: Int, scope: CoroutineScope) {
val itemInfo = this.layoutInfo.visibleItemsInfo.firstOrNull { it.index == index }
scope.launch {
when {
itemInfo != null -> {
val center = this@animateScrollAndCentralizeItem.layoutInfo.viewportEndOffset / 2
val childCenter = itemInfo.offset + itemInfo.size / 2
this@animateScrollAndCentralizeItem.animateScrollBy((childCenter - center).toFloat())
}
else -> {
this@animateScrollAndCentralizeItem.animateScrollToItem(index)
}
}
}
}
@EmmanuelGuther
Copy link
Author

LazyColumn(
state = listState,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(rankingUIModel.rankingUIModel.challengeRankingItems) {
ItemQualifying(modifier= Modifier, item = it, onRankingItemPressed = onRankingItemPressed)
}

            coroutineScope.launch {
                rankingUIModel.rankingUIModel.challengeRankingItems.firstOrNull { it.isCurrentUser }
                    ?.let { itCurrentUserItem ->
                        rankingUIModel.rankingUIModel.challengeRankingItems.indexOfFirst { it == itCurrentUserItem }
                            .let { i ->
                                listState.animateScrollAndCentralizeItem(i, this)
                            }
                    }
            }
        }

@maxrave-dev
Copy link

It only works when all items have same size (height)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment