添加新项目时滚动到顶部



我有一个用例,我想一个LazyColumn滚动到顶部,如果一个新的项目被添加到列表的开始-但只有当列表滚动到顶部之前。我目前正在使用键来自动记录滚动位置,这对于所有其他情况都很好,而不是当滚动状态位于列表顶部时。

这类似于我在应用程序中的实际逻辑(在我的情况下,没有按钮,showFirstItem是可组合函数的参数,由其他一些逻辑控制):

var showFirstItem by remember { mutableStateOf(true) }
Column {
Button(onClick = { showFirstItem = !showFirstItem }) {
Text("${if (showFirstItem) "Hide" else "Show"} first item")
}
LazyColumn {
if (showFirstItem) {
item(key = "first") {
Text("First item")
}
}
items(count = 100,
key = { index ->
"item-$index"
}
) { index ->
Text("Item $index")
}
}
}

作为一个例子,我希望看到"第一项"如果我滚动到顶部,隐藏项目,他们会再次显示它。或隐藏项目,滚动到顶部,然后再次显示。

我认为解决方案可能与LaunchedEffect有关,但我不确定。

如果添加了一个新项并且user位于顶部,则除非将列表滚动到顶部,否则新项不会出现。我试过了:

if (lazyListState.firstVisibleItemIndex <= 1) {
//scroll to top to ensure latest added book gets visible
LaunchedEffect(key1 = key) {
lazyListState.scrollToItem(0)
}
}
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = lazyListState
) {...

它似乎有效。但它打破了我正在使用的刷新组件的拉。不知道怎么解。我还在努力强迫自己喜欢作曲。希望这一天会到来=)

您可以像这样滚动到LazyColumn的列表顶部:

val coroutineScope = rememberCoroutineScope()
...
Button(onClick = {
coroutineScope.launch {
// 0 is the first item index
scrollState.animateScrollToItem(0)
}
}) {
Text("Scroll to the top")
}

因此,在您需要从协程中调用scrollState.animateScrollToItem(0)时,例如在添加新项之后。

在您的条目添加逻辑中,

scrollState.animateScrollToItem(0)
//Add an optional delay here
showFirst = ... //Handle here whatever you want

这里,scrollState将在LazyColumn

中传递val scrollState = rememberScrollState() LazyColumn(state = scrollState) { ... }

最新更新