如何使用 Jetpack Compose AdapterList 保留滚动位置?

Yur*_*kov 6 android kotlin android-jetpack-compose

我有一个带有使用 Jetpack Compose 构建的 List-Detail 流的应用程序。从详细信息视图返回到列表视图时,我想保留滚动位置

根据模型状态交换表面:

@Composable
private fun AppContent() {
    val scrollerPosition = ScrollerPosition()
    Crossfade(State.currentScreen) { screen ->
        Surface(color = MaterialTheme.colors.background) {
            when (screen) {
                is Screen.List -> ListScreen(scrollerPosition)
                is Screen.Details -> DetailsScreen(screen.transaction)
                is Screen.New -> NewScreen()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ListScreen 曾经有一个 VerticalScroller,我给它一个 ScrollerPosition 以在屏幕更改后保留位置。但是,此解决方案不适用于 AdapterList。

这是以前的样子:

@Composable
private fun TransactionsList(modifier: Modifier, scrollerPosition: ScrollerPosition) {
    Box(modifier = modifier.fillMaxSize().wrapContentSize(Alignment.Center)) {
        VerticalScroller(scrollerPosition = scrollerPosition) {
            AdapterList(State.transactions, itemCallback = { transaction ->
                TransactionListRow(transaction)
                ListDivider()
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何让 AdapterList 保持滚动位置?

@Composable
private fun TransactionsList(modifier: Modifier, scrollerPosition: ScrollerPosition) {
    Box(modifier = modifier.fillMaxSize().wrapContentSize(Alignment.Center)) {
        AdapterList(State.transactions, itemCallback = { transaction ->
            TransactionListRow(transaction)
            ListDivider()
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

Yur*_*kov 0

借助 Jetpack Compose 1.0,使用 可以保持滚动位置rememberLazyListState()

要保留状态,请在树中足够高的位置初始化状态变量,例如导航上方。然后将其传递给LazyColumn.

Crossfade这是一个在列表和详细信息之间切换时保留列表中的滚动位置的示例:

  val listState = rememberLazyListState()

  Crossfade(screen) { scr ->
    Surface(color = colors.background) {
      when (scr) {
        is Screen.List -> LazyColumn(state = listState) {
              items(items) { item ->
                // here come the items
              }
            }
        is Screen.Details -> DetailsScreen()
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

的大小items必须保持不变才能正常工作。