这是我的简化代码:
val scrollBehavior = BottomAppBarDefaults.exitAlwaysScrollBehavior()
val isCollapsed = scrollBehavior.state.collapsedFraction != 1.0f
val listState = rememberLazyListState()
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0),
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
bottomBar = {
AnimatedVisibility(!listState.canScrollBackward || !isCollapsed) {
BottomAppBar(scrollBehavior = scrollBehavior) {
//...
Button(onClick = {
scope.launch {
listState.animateScrollToItem(0)
}
}) {
Text("Scroll to top")
}
}
}
}
)
isCollapsed
和!listState.canScrollBackward
用于确定是否应显示BottomAppBar。
我在 issuetracker 上看到了这样的实现。但它对我不起作用。
期望的结果是什么,在初始状态下,BottomBar 显示,当我们向下滚动时,它隐藏,当我们向上滚动时,我们显示它,当我们单击按钮时,我们返回到最开始并显示 BottomBar?
你可以这样做:
val scrollBehavior = BottomAppBarDefaults.exitAlwaysScrollBehavior()
val isCollapsed = scrollBehavior.state.collapsedFraction == 1.0f
val listState = rememberLazyListState()
val scope = rememberCoroutineScope()
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0),
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
bottomBar = {
AnimatedVisibility(!isCollapsed) {
BottomAppBar(scrollBehavior = scrollBehavior) {
Button(onClick = { scope.launch { listState.animateScrollToItem(0) } }) {
Text("Scroll to top")
}
}
}
}
) { paddingValues ->
LazyColumn(
Modifier
.fillMaxSize()
.padding(paddingValues),
state = listState
) {
items(200) { index ->
Text(modifier = Modifier.fillMaxWidth(), text = "Title $index")
}
}
}