首页 > 解决方案 > Jetpack Compose 中的长按手势

问题描述

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

这是一个显示动画的 gif。

Spotify 卡

标签: androidkotlinandroid-jetpack-compose

解决方案


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

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
        })
}

在此处输入图像描述


推荐阅读