I am trying to get the scroll percentage of lazy columns to scroll like 25%, 50%, 100%. After the analysis, I could not find any method to get it.
Asked
Active
Viewed 687 times
1
-
1There is no easy way and the advantage of `LazyColumns` is that they only compose items that will potentially become visible soon, so unless you know (or you can calculate) the height of your items (in advance) you can't know the exact scroll percentage. But if you can do that, then you can calculate the exact scroll offset and scroll percentage also for a `LazyColumn`. So what are your limitations? Do you know (or can you set) the height of items in your LazyColumn(s) or is the height of your items dynamic? – Ma3x Jul 22 '22 at 20:05
-
@Ma3x I have multiple components with different heights inside of LazyColumn that are loaded dynamically. That is the limitation I am facing – Asharali V U Jul 25 '22 at 03:06
-
By "loaded dynamically" do you mean just displayed dynamically by the `LazyColumn` or actually loaded dynamically from an external source as you scroll? My question still stands: do you know how many items of each type will you be loading or you don't know their type and height until you have actually loaded them? That distinction is important, it is the difference between possible and impossible to calculate the scroll percentage. Maybe updating the question with your `LazyColumn` code could give us some insight too. – Ma3x Jul 25 '22 at 05:11
1 Answers
2
You can find it based on the visible index since the items are loaded lazily:
@Composable
fun ScrollPercentageLazyColumn() {
val itemsCount = 500
val scrollState = rememberLazyListState()
val formatter = remember { DecimalFormat("0.0") }
val firstVisibleItemIndex = scrollState.firstVisibleItemIndex
val visibleItemsCount = scrollState.layoutInfo.visibleItemsInfo.size
val percent = (firstVisibleItemIndex / (itemsCount - visibleItemsCount).toFloat()) * 100f
val scrollText = "scroll percentage : ${formatter.format(percent)}%"
Box {
LazyColumn(
state = scrollState,
modifier = Modifier.fillMaxSize()
) {
items(itemsCount) {
Text(text = "Item $it", Modifier.padding(12.dp))
}
}
Text(text = scrollText, Modifier.align(Alignment.TopCenter).padding(8.dp))
}
}

Hamed Goharshad
- 631
- 4
- 12
-
Sure, this function shows an idea but you can customize it to support your use case as well – Hamed Goharshad Aug 08 '22 at 17:23