Jetpack Compose中粘性头部折叠后异常固定在顶部的问题求助
Jetpack Compose中粘性头部折叠后异常固定在顶部的问题求助
嘿,各位Compose大佬,我最近在做一个带可折叠粘性头部的列表,逻辑是每个Section的头部可以点击展开/折叠对应的子项,代码逻辑看起来没问题,但实际运行时出现了奇怪的bug:
当我折叠某个Section(比如Section A)之后,再滚动列表,这个已经折叠的头部会一直固定在屏幕顶部,哪怕我滚动到了后面的Section(比如Section E),它还是不消失,本该显示当前滚动位置对应的粘性头部(比如Section D)的时候,依然是折叠的A头卡在上面。哪怕之后再把A展开,这个问题还是存在。
先给大家看看我的代码:
数据类与数据源
data class Section( val header: String, val items: List<String> ) val sections = listOf( Section("A", listOf("A Item 1", "A Item 2", "A Item 3", "A Item 4", "A Item 5", "A Item 6")), Section("B", listOf("B Item 1", "B Item 2", "B Item 3", "B Item 4", "B Item 5", "B Item 6", "B Item 7", "B Item 8", "B Item 9")), Section("C", listOf("C Item 1", "C Item 2", "C Item 3", "C Item 4", "C Item 5", "C Item 6", "C Item 7", "C Item 8", "C Item 9", "C Item 10")), Section("D", listOf("D Item 1", "D Item 2", "D Item 3", "D Item 4", "D Item 5")), Section("E", listOf("E Item 1", "E Item 2")), Section("F", listOf("F Item 1", "F Item 2", "F Item 3")), Section("G", listOf("G Item 1", "G Item 2", "G Item 3", "G Item 4", "G Item 5")) )
可组合函数实现
@Composable fun MyScreen() { val expandMap = remember { mutableStateMapOf<String, Boolean>().apply { putAll(sections.associate { it.header to true }) } } LazyColumn { sections.forEach { section -> stickyHeader { Surface( onClick = { expandMap[section.header] = !(expandMap[section.header] ?: false) }, color = MaterialTheme.colorScheme.tertiary, ) { Row( Modifier .padding(8.dp) .fillMaxWidth() ) { ExposedDropdownMenuDefaults.TrailingIcon(expandMap[section.header] ?: false) Spacer(Modifier.width(8.dp)) Text(section.header) } } } if (expandMap[section.header] ?: false) { items(section.items) { Row( Modifier .fillMaxWidth() .wrapContentHeight() .padding(8.dp) ) { Text(it) } } } } } }
问题复现步骤
- 初始状态所有Section都是展开的,滚动到后面的Section(比如E),粘性头部正常显示当前对应的Section头;
- 折叠前面的某个Section(比如A),再滚动到E,此时顶部依然固定显示A的头部,而不是当前应该显示的D头部;
- 哪怕再把A展开,滚动时这个异常依然存在。
我已经尝试给stickyHeader添加key参数和contentType,但问题还是没解决。我用的版本是composeMultiplatform = "1.8.2",kotlin = "2.2.0"。
有没有大佬遇到过类似的问题?或者能帮我看看哪里逻辑错了吗?
内容来源于stack exchange




