简体   繁体   English

在 Jetpack Compose 中为自定义手势添加涟漪效果

[英]Add ripple effect to a custom gesture in Jetpack Compose

I try to create a tappable surface in Jetpack Compose where the elevation changes when the user taps the surface.我尝试在 Jetpack Compose 中创建一个可点击的表面,当用户点击表面时,高度会发生变化。 The following code already works:以下代码已经有效:

var tapped by remember { mutableStateOf(false) }
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)
         .pointerInput(Unit) {
              detectTapGestures(onPress = {
              tapped = true

              tryAwaitRelease()

              tapped = false
         })
    },
    elevation = elevation
) {
  ...
}

However I would like to have a ripple effect during the tap.但是,我希望在点击过程中产生涟漪效应。 How could I achieve this?我怎么能做到这一点?

The default button/surface onClick and clickable is not suitable because it only handles press inputs but no taps.默认的按钮/表面onClickclickable不适合,因为它只处理按下输入而不处理点击。

You use Modifier.indication to add ripple effect, and pass events with interactionSource to update it state like this:您可以使用Modifier.indication添加涟漪效果,并通过interactionSource传递事件以更新它的状态,如下所示:

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)
        .indication(interactionSource, LocalIndication.current)
        .pointerInput(Unit) {
            detectTapGestures(onPress = { offset ->
                tapped = true

                val press = PressInteraction.Press(offset)
                interactionSource.emit(press)

                tryAwaitRelease()

                interactionSource.emit(PressInteraction.Release(press))

                tapped = false
            })
        },
    elevation = elevation
) {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM