如何从 Scroll from Android Compose 获取滚动的百分比或总数?

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

我需要使用 Android Compose with states provided from ScrollState or NestedScrollState 在任何屏幕上获取屏幕上滚动总数的百分比,如何获取此信息?

您可以从 ScrollState class 的 valuemaxValue 字段中获取。

@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))
    }
}

如果您需要使用 LazyColumn 实现此逻辑,我认为您可以基于可见索引来实现,因为项目是延迟加载的。

@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))
    }
}