Jetpack Compose 中的长按手势

时间:2021-05-29 13:51:46

标签: android kotlin android-jetpack-compose

如何在长按时使用jetpack compose获得此内容大小减小动画,然后在释放时恢复正常(如Spotify Android App中的卡片)。

这是显示动画的 gif。

Spotify Card

1 个答案:

答案 0 :(得分:4)

您可以使用 Transition 来管理按下和释放状态之间的动画。

enum class ComponentState { Pressed, Released }

var toState by remember { mutableStateOf(ComponentState.Released) }
val transition: Transition<ComponentState> = updateTransition(targetState = toState, label = "")

// Defines a float animation to scale x,y
val scalex: Float by transition.animateFloat(
    transitionSpec = { spring(stiffness = 50f) }, label = ""
) { state ->
    if (state == ComponentState.Pressed) 0.90f else 1f
}
val scaley: Float by transition.animateFloat(
    transitionSpec = { spring(stiffness = 50f) }, label = ""
) { state ->
    if (state == ComponentState.Pressed) 0.90f else 1f
}

然后您可以使用 PointerInputScope.detectTapGestures 来检测按下手势:

val modifier = Modifier.pointerInput(Unit) {
    detectTapGestures(
        onPress = {
            toState = ComponentState.Pressed
            tryAwaitRelease()
            toState = ComponentState.Released
        }
    )
}

最后将动画应用到您的 Composable。
例如:

Box(
    modifier
        .width((100 * scalex).dp)
        .height((100 * scaley).dp),
    contentAlignment = Alignment.Center) {

    Image(
        //...
        modifier = Modifier.graphicsLayer{
            scaleX = scalex;
            scaleY = scaley
        })
}

enter image description here