Jetpack Compose Paging 3 自动滚动到顶部 [英] Jetpack Compose Paging 3 Auto scroll to the top

查看:200
本文介绍了Jetpack Compose Paging 3 自动滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的是page 3,显示数据的时候,发现如果页面切换回到最底页,数据会自动滚到最上面.

I am using page 3, when displaying data, I found that if the page switches and returns to the bottom page, the data will automatically roll to the top.

如果有两个项目,它会自动滚动到顶部,如果有一个项目,没有问题

val pagingItems = viewModel.windList.collectAsLazyPagingItems()

LazyColumn(Modifier.fillMaxSize()) {
    item {
        ...
    }
    items(pagingItems) { wind ->
        if (wind != null) {
            WindRow(navController, wind)
        }
    }
}

这种方式很好

LazyColumn(Modifier.fillMaxSize()) {
    items(pagingItems) { wind ->
        if (wind != null) {
            WindRow(navController, wind)
        }
    }
}

我不可避免地会使用多个项目.我该如何解决?

I inevitably use multiple items. How can I solve it?

推荐答案

如果我的理解正确,每次加载新页面都会导致您滚动到顶部,并在 LazyColumn.

If I'm understanding correctly, every new page load causes you to scroll to top with a static item at the top of your LazyColumn.

我对这里发生的事情的最佳猜测是在没有在示例中实际尝试的情况下,在每次加载新页面时,paging-compose 将列表重新提交给 LazyColumn.由于有一个静态项目始终在那里,Compose 将保持该项目在视野中,并且由于该静态项目位于顶部,因此具有滚动到顶部的效果.

My best guess at what is happening here without actually trying it out in a sample, is that on every new page load, paging-compose resubmits the list to LazyColumn. Since there is a static item that is always there though, Compose will keep that item in view, and because that static item is at the top it has the effect of scrolling to top.

作为解决方法,您可以使用 Paging 的 对标头的内置支持

For a workaround, you could just use Paging's built-in support for headers

ViewModel.kt

ViewModel.kt

val windList = Pager(..) { ..}
  .map { pagingData ->
    pagingData.insertHeaderItem(..)
  }
  .cachedIn(viewModelScope)
  .collectAsLazyPagingItems()

此外,我建议在项目中实现键映射,因为它将帮助您为 Compose 的 LazyColumn 提供稳定的 ID,使其了解如何在刷新或配置更改时恢复滚动位置.

Also, I would recommend to implement the key mapping in items, as it will help you provide stable ids to Compose's LazyColumn, allowing it to understand how to resume scroll position on refresh or config change.

这篇关于Jetpack Compose Paging 3 自动滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆