我有一个可重用的布局,包含一个LazyColumn
和一个滚动到LazyColumn
顶部的按钮。声明按钮(并确保click事件有效)的最有效方法是什么,这样我就不必在每次创建新屏幕时都对其进行decaler?
@Composable
fun MyReusableScaffold(scaffoldTitle: String, scaffoldContent: @Composable () -> Unit) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = { Text(text = scaffoldTitle) },
scrollBehavior = scrollBehavior
)
},
content = { contentPadding ->
scaffoldContent(contentPadding = contentPadding)
}
)
}
@Composable
fun MyScreen(navController: NavController) {
MyReusableScaffold(
scaffoldTitle = "Hello Android",
scaffoldContent = {
MyScreenContent(contentPadding = it)
}
)
}
@Composable
fun MyScreenContent(modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues()) {
LazyColumn(
state = listState,
contentPadding = contentPadding,
) {
items(22) {
ListItem(it)
}
}
val showButton by remember {
derivedStateOf {
listState.firstVisibleItemIndex > 0
}
}
AnimatedVisibility(
visible = showButton,
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier.align(BottomCenter)
) {
ScrollToTopButton(onClick = {
coroutineScope.launch {
listState.animateScrollToItem(index = 0)
}
})
}
}
@Composable
fun ScrollToTopButton(onClick: () -> Unit) {
Box(
Modifier
.fillMaxSize()
) {
Button(
onClick = { onClick() }
) {
Text(text = stringResource(id = R.string.top))
}
}
}
1条答案
按热度按时间tkqqtvp11#
您可以移动
ScrollToTopButton
内部的所有逻辑。类似于:
然后在所有屏幕中使用: