'How get the percentage or total scrolled from Scroll from Android Compose?

i need get the percentage of total scrolled on Screen using Android Compose with states provides from ScrollState or NestedScrollState in any screen, how get this informations?



Solution 1:[1]

You can get that from value and maxValue fields of ScrollState class.

@Composable
fun ScrollTestWithColumn() {
    val formatter = remember { DecimalFormat("0.0")} // optional
    val scrollState = rememberScrollState()
    val percent = (scrollState.value.toFloat() / scrollState.maxValue.toFloat()) * 100f
    val scrollText = "scroll: ${formatter.format(percent)}"
    Box {
        Column(
            Modifier
                .fillMaxSize()
                .verticalScroll(scrollState)
        ) {
            repeat(200) {
                Text(text = "Item $it", Modifier.padding(16.dp))
            }
        }
        Text(text = scrollText, Modifier.align(Alignment.BottomEnd))
    }
}

If you need to implement this logic with a LazyColumn, I think you can do it based on visible index since the items are loaded lazily.

@Composable
fun ScrollTestWithLazyColumn() {
    val formatter = remember { DecimalFormat("0.0") }
    val scrollState = rememberLazyListState()
    val totalItemsCount = 200
    val firstVisibleIndex = scrollState.firstVisibleItemIndex
    val visibleItemsCount = scrollState.layoutInfo.visibleItemsInfo.size
    val percent = (firstVisibleIndex / (totalItemsCount - visibleItemsCount).toFloat()) * 100f
    val scrollText = "scroll: ${formatter.format(percent)}"
    Box {
        LazyColumn(
            state = scrollState,
            modifier = Modifier.fillMaxSize()
        ) {
            items(totalItemsCount) {
                Text(text = "Item $it", Modifier.padding(16.dp))
            }
        }
        Text(text = scrollText, Modifier.align(Alignment.BottomEnd))
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1