Jetpack Compose 中的长按手势

sun*_*525 1 android kotlin android-jetpack-compose

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

这是显示动画的 gif。

Spotify 卡

Gab*_*tti 5

You can use a Transition to manage the animations between the pressed and release states.

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
}
Run Code Online (Sandbox Code Playgroud)

Then you can use the PointerInputScope.detectTapGestures to detect the press gestures:

val modifier = Modifier.pointerInput(Unit) {
    detectTapGestures(
        onPress = {
            toState = ComponentState.Pressed
            tryAwaitRelease()
            toState = ComponentState.Released
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

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

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

    Image(
        //...
        modifier = Modifier.graphicsLayer{
            scaleX = scalex;
            scaleY = scaley
        })
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明