使用 Paging 3 时保存并保留 LazyColumn 滚动位置

Anu*_*nth 11 kotlin android-jetpack android-jetpack-navigation android-jetpack-compose

我在我的活动中使用 Paging 3 Library with Lazy Column 和 BottomNavigation Menu。附加到 BottomNavMenu 的每个可组合屏幕都使用一个可组合,而后者又使用惰性列。当我使用 compose 导航库在可组合物之间导航时,我希望重新组合的可组合物保留滚动位置和 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
Run Code Online (Sandbox Code Playgroud)

每次我导航到这个可组合时,它都会重新组合,滚动位置设置为 0,这不是我想要的。处理这个问题的正确方法是什么

Cyr*_*ind 7

collectAsLazyPagingItems()在声明您的身份之前您可能需要做NavHost

我提交了一个关于此问题的错误,您可以阅读它以了解更多详细信息并加注星标以关注该问题: https ://issuetracker.google.com/issues/177245496

  • 这个错误仍然存​​在。它与导航撰写无关,因为我的应用程序甚至不使用导航撰写。 (2认同)

And*_*ska 7

您可以在 ViewModel 中缓存分页数据,然后在 UI 中收集它。ViewModel 部分看起来像这样:

val items: Flow<PagingData<YourItem>> =
    Pager(PagingConfig(PAGE_SIZE)) {
        YourSource()
    }
    .flow
    .cachedIn(viewModelScope)
Run Code Online (Sandbox Code Playgroud)

然后你可以在 UI 中使用它,如下所示:

@Composable
fun YourScreen(viewModel: YourViewModel) {
    val items = viewModel.items.collectAsLazyPagingItems()
    ...
}
Run Code Online (Sandbox Code Playgroud)