You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose自定义tap手势如何添加ripple水波纹效果?

解决方案

你可以通过手动添加交互源和水波纹标识的方式实现需求,不需要依赖默认clickable逻辑,完全保留你自定义的手势处理:

var tapped by remember { mutableStateOf(false) }
// 新增:存储交互状态,给水波纹提供事件源
val interactionSource = remember { MutableInteractionSource() }
val elevation by animateDpAsState(
    targetValue = if (tapped) 0.dp else 5.dp,
    animationSpec = tween(50)
)

Surface(
    shape = RoundedCornerShape(20.dp),
    modifier = Modifier
         .padding(16.dp)
         .requiredSize(150.dp)
         // 新增:绑定交互源和水波纹效果
         .interactionSource(interactionSource)
         .indication(
             indication = LocalIndication.current,
             interactionSource = interactionSource
         )
         .pointerInput(Unit) {
              detectTapGestures(onPress = {
                  tapped = true
                  tryAwaitRelease()
                  tapped = false
              })
         },
    elevation = elevation
) {
  ...
}

如果需要自定义水波纹的颜色、透明度等样式,可以在外层包裹CompositionLocalProvider重写水波纹主题:

CompositionLocalProvider(
    LocalRippleTheme provides object : RippleTheme {
        @Composable
        override fun defaultColor() = RippleTheme.defaultRippleColor(Color.Red, lightTheme = true)

        @Composable
        override fun rippleAlpha() = RippleTheme.defaultRippleAlpha(Color.Red, lightTheme = true)
    }
) {
    // 上述Surface代码放在此处即可生效自定义红色水波纹
}

关键说明

  • MutableInteractionSource是水波纹效果依赖的交互事件存储载体,用来接收按压、释放等交互状态
  • indication修饰符传入默认的LocalIndication.current就会加载系统默认的水波纹效果,你也可以传入自定义Indication实现其他按下效果
  • 原有自定义pointerInput的手势逻辑完全不受影响,能同时满足阴影动画和水波纹的需求

内容的提问来源于stack exchange,提问作者oldu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:57:03