在Android Jetpack Compose中实现粘性UI垂直滚动的方法如下所示:
在gradle.build文件中添加以下依赖: implementation "androidx.compose.foundation:foundation:$compose_version" implementation "androidx.compose.foundation:foundation-layout:$compose_version"
创建一个VerticalScroller,将WholeContent放在它内部,并使用Modifier.stickyHeader在PersistentHeader之上添加粘性Header。
@Composable fun StickyUiVerticalScroll() { VerticalScroller(modifier = Modifier.fillMaxSize()) { Column { PersistentHeader() WholeContent() } } }
@Composable fun PersistentHeader() { Box( modifier = Modifier .stickyHeader { // Set the height equal to the height of the header to make sure // the content scrolls underneath it properly. overlay { Header() } } .background(Color.White) .height(HeaderHeight) .fillMaxWidth() ) { Text( text = "This is a sticky header", modifier = Modifier.align(Alignment.Center) ) } }
@Composable fun WholeContent() { Column(modifier = Modifier.fillMaxWidth()) { repeat(50) { index -> Row(modifier = Modifier.padding(16.dp)) { Text(text = "Item $index", modifier = Modifier.weight(1f)) Button(onClick = {}) { Text(text = "Click Me!") } } Divider(color = Color.Black) } } }
@Composable fun Header() { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text( text = "Sticky Header", fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) } }
private val HeaderHeight = 60.dp
setContent { MaterialTheme { Surface { StickyUiVertical