如何在Jetpack Compose中移除或修改任意视图的点击水波纹效果
问题原因
你之前的操作不生效,是因为NavigationBarItem内部已经内置了点击事件逻辑,外层追加的clickable修饰符无法覆盖内部的点击配置,因此修改indication参数不会生效。
方案1:完全移除水波纹效果
方法A:直接使用官方暴露参数配置(推荐)
androidx.compose.material3 1.2.0及以上版本的NavigationBarItem已经直接暴露了interactionSource和indication参数,直接配置即可关闭水波纹:
var selectedItem by remember { mutableStateOf(0) } val items = listOf("Songs", "Artists", "Playlists") NavigationBar { items.forEachIndexed { index, item -> val interactionSource = remember { MutableInteractionSource() } NavigationBarItem( icon = { Icon(Icons.Filled.Favorite, contentDescription = null) }, label = { Text(item) }, selected = selectedItem == index, onClick = { selectedItem = index }, // 核心配置:indication设为null即可关闭水波纹 interactionSource = interactionSource, indication = null ) } }
方法B:自定义Ripple主题适配低版本
如果你的Material3依赖版本较低,找不到上述参数,可以通过覆盖局部水波纹主题实现效果:
- 先定义无水波纹的主题实现
private object NoRippleTheme : RippleTheme { @Composable override fun defaultColor() = Color.Transparent @Composable override fun rippleAlpha(): RippleAlpha = RippleAlpha(0f, 0f, 0f, 0f) }
- 包裹目标组件覆盖主题
var selectedItem by remember { mutableStateOf(0) } val items = listOf("Songs", "Artists", "Playlists") NavigationBar { items.forEachIndexed { index, item -> CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) { NavigationBarItem( icon = { Icon(Icons.Filled.Favorite, contentDescription = null) }, label = { Text(item) }, selected = selectedItem == index, onClick = { selectedItem = index } ) } } }
如果需要给整个页面关闭水波纹,直接把CompositionLocalProvider套在页面根布局外层即可。
方案2:自定义水波纹效果
如果不需要完全移除水波纹,仅需要修改水波纹的颜色、透明度等属性,自定义对应的RippleTheme即可:
private object CustomRippleTheme : RippleTheme { // 自定义水波纹颜色 @Composable override fun defaultColor() = Color(0xFFE91E63) // 自定义不同状态下的水波纹透明度 @Composable override fun rippleAlpha(): RippleAlpha = RippleAlpha( pressedAlpha = 0.4f, focusedAlpha = 0.2f, draggedAlpha = 0.3f, hoveredAlpha = 0.1f ) }
后续使用方式和方案1的方法B一致,通过CompositionLocalProvider覆盖局部LocalRippleTheme即可生效。
内容的提问来源于stack exchange,提问作者Stefano Sansone
相关产品推荐
相关产品推荐

