使用 Paging 3 时保存并保留 LazyColumn 滚动位置
Save and retain LazyColumn scroll position while using Paging 3
我在 Activity 中使用带有 Lazy Column 和 BottomNavigation 菜单的 Paging 3 库。每个附加到 BottomNavMenu 的可组合屏幕都使用一个可组合项,而后者又使用惰性列。当我使用组合导航库在可组合项之间导航时,我希望重组的可组合项保留滚动位置和 lazyListState
我尝试了以下但不起作用:
val listState = rememberLazyListState()
val scrollState = rememberScrollState()
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 56.dp)
.scrollable(scrollState, Orientation.Vertical),
state = listState,
) {
//draw the items and hook the loadState to the lazy paging items
每次我导航到这个可组合项时,它都会重新组合,滚动位置设置为 0,这不是我想要的。
正确的处理方式是什么
您可能需要在声明您的 NavHost
之前执行 collectAsLazyPagingItems()
我提交了一个关于此的错误,您可以阅读它以获取更多详细信息并为其加注星标以关注该问题:
https://issuetracker.google.com/issues/177245496
这似乎是 Compose Navigation 组件中的一个错误。
rememberLazyListState()
在 NavHost
.
内的可组合项的配置更改(屏幕旋转、深色主题切换等)上无法正常工作
您可以在 ViewModel 中缓存分页数据,然后在 UI 中收集它。 ViewModel 部分看起来像这样:
val items: Flow<PagingData<YourItem>> =
Pager(PagingConfig(PAGE_SIZE)) {
YourSource()
}
.flow
.cachedIn(viewModelScope)
然后你可以像这样在 UI 中使用它:
@Composable
fun YourScreen(viewModel: YourViewModel) {
val items = viewModel.items.collectAsLazyPagingItems()
...
}
我在 Activity 中使用带有 Lazy Column 和 BottomNavigation 菜单的 Paging 3 库。每个附加到 BottomNavMenu 的可组合屏幕都使用一个可组合项,而后者又使用惰性列。当我使用组合导航库在可组合项之间导航时,我希望重组的可组合项保留滚动位置和 lazyListState
我尝试了以下但不起作用:
val listState = rememberLazyListState()
val scrollState = rememberScrollState()
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 56.dp)
.scrollable(scrollState, Orientation.Vertical),
state = listState,
) {
//draw the items and hook the loadState to the lazy paging items
每次我导航到这个可组合项时,它都会重新组合,滚动位置设置为 0,这不是我想要的。 正确的处理方式是什么
您可能需要在声明您的 NavHost
collectAsLazyPagingItems()
我提交了一个关于此的错误,您可以阅读它以获取更多详细信息并为其加注星标以关注该问题: https://issuetracker.google.com/issues/177245496
这似乎是 Compose Navigation 组件中的一个错误。
rememberLazyListState()
在 NavHost
.
您可以在 ViewModel 中缓存分页数据,然后在 UI 中收集它。 ViewModel 部分看起来像这样:
val items: Flow<PagingData<YourItem>> =
Pager(PagingConfig(PAGE_SIZE)) {
YourSource()
}
.flow
.cachedIn(viewModelScope)
然后你可以像这样在 UI 中使用它:
@Composable
fun YourScreen(viewModel: YourViewModel) {
val items = viewModel.items.collectAsLazyPagingItems()
...
}