I want to use Column instead of LazyColumn, and make it scrollable by Modifier.verticalScroll(scrollState)
, is there any way to get currently visible items key that users see on the screen?
CodePudding user response:
I'm not positive that I fully understand, so this may be off base but here's some code that keeps track of the position of the items within a scrollable column and updates a text whenever the first visible item changes. Performance seems okay, at least for a list of items that would be reasonable for a non-lazy column.
@Composable
fun Example() {
val positions = remember { items.map { 0f }.toMutableStateList() }
val ss = rememberScrollState()
val firstVisibleItem by remember {
derivedStateOf {
positions.indexOfLast {
it <= ss.value
}
}
}
Column(Modifier.fillMaxSize()) {
Text(
items.getOrElse(firstVisibleItem) { "None "},
Modifier
.fillMaxWidth()
.background(Color.LightGray)
.padding(16.dp)
)
Column(
Modifier
.verticalScroll(ss)
.fillMaxSize()
.padding(16.dp)
) {
items.forEachIndexed { index, item ->
Text(
text = item,
modifier = Modifier
.height(100.dp)
.onGloballyPositioned {
positions[index] = it.positionInParent().y
}
)
}
}
}
}
As an aside, I'd be surprised if a normal scrollable column had better performance than a lazy one unless the item count is very small.