Jetpack Compose Material3如何实现禁用状态的ListItem组件?
实现Material3禁用状态的ListItem
你的ListItem组件缺少enabled状态控制参数,且所有颜色获取逻辑都硬编码为enabled = true,导致无法切换禁用样式。按以下方式修改即可实现需求:
1. 新增enabled控制参数
在ListItem函数签名中添加enabled: Boolean = true参数,允许外部传入状态值。
2. 替换硬编码的enabled值
将所有调用headlineColor、leadingIconColor、trailingIconColor时的enabled = true,替换为传入的enabled参数。
3. 补充禁用态交互处理(可选)
禁用状态下通常需要拦截点击事件,并取消视觉上的elevation效果,让组件看起来更“不可交互”。
修改后的完整代码示例
@Composable @ExperimentalMaterial3Api fun ListItem( headlineText: @Composable () -> Unit, modifier: Modifier = Modifier, overlineText: @Composable (() -> Unit)? = null, supportingText: @Composable (() -> Unit)? = null, leadingContent: @Composable (() -> Unit)? = null, trailingContent: @Composable (() -> Unit)? = null, colors: ListItemColors = ListItemDefaults.colors(), tonalElevation: Dp = ListItemDefaults.Elevation, shadowElevation: Dp = ListItemDefaults.Elevation, enabled: Boolean = true, // 新增状态控制参数 ) { if (overlineText == null && supportingText == null) { // 处理禁用态的交互拦截与样式调整 val containerModifier = if (!enabled) { modifier.pointerInput(enabled) { awaitPointerEventScope { // 禁用时拦截所有点击事件 awaitFirstDown(false) } } } else { modifier } ListItem( modifier = containerModifier, containerColor = colors.containerColor().value, contentColor = colors.headlineColor(enabled = enabled).value, // 禁用时取消elevation tonalElevation = tonalElevation.takeIf { enabled } ?: 0.dp, shadowElevation = shadowElevation.takeIf { enabled } ?: 0.dp, minHeight = ListTokens.ListItemContainerHeight, paddingValues = PaddingValues(ListItemHorizontalPadding, ListItemVerticalPadding) ) { leadingContent?.let { leadingContent( leadingContent = leadingContent, contentColor = colors.leadingIconColor(enabled = enabled).value, topAlign = false )() } Box( Modifier .weight(1f) .align(Alignment.CenterVertically) ) { ProvideTextStyleFromToken( colors.headlineColor(enabled = enabled).value, ListTokens.ListItemLabelTextFont, headlineText ) } trailingContent?.let { trailingContent( trailingContent = trailingContent, contentColor = colors.trailingIconColor(enabled = enabled).value, topAlign = false )() } } } // 可补充多行ListItem的处理逻辑,同样替换enabled参数即可 }
使用示例
ListItem( headlineText = { Text("禁用状态列表项") }, enabled = false, // 传入false启用禁用态 leadingContent = { Icon(Icons.Default.Info, contentDescription = null) } )
修改后效果:
- 当
enabled=false时,文本、图标自动切换为Material3定义的禁用态颜色 - 列表项取消elevation,视觉上呈现灰化效果
- 点击事件被拦截,无法触发交互
内容的提问来源于stack exchange,提问作者sapaza
相关产品推荐
相关产品推荐

