简体   繁体   English

在 Jetpack Compose 中的可拖动项目上重置偏移量 animation

[英]Reset offset animation on draggable item in Jetpack Compose

I have a green square that I can drag vertically.我有一个可以垂直拖动的绿色方块。 But whenever I stop dragging it, I want it to reset the offset to the start with an animation.但是每当我停止拖动它时,我希望它用 animation 将偏移量重置为开头。 I tried it like this, but I can't figure it out.我试过这样,但我无法弄清楚。 Does someone know how to do it?有人知道该怎么做吗?

@Composable
fun DraggableSquare() {
    var currentOffset by remember { mutableStateOf(0F) }
    val resetAnimation by animateIntOffsetAsState(targetValue = IntOffset(0, currentOffset.roundToInt()))

    var shouldReset = false

    Box(contentAlignment = Alignment.TopCenter, modifier = Modifier.fillMaxSize()) {
        Surface(
            color = Color(0xFF34AB52),
            modifier = Modifier
                .size(100.dp)
                .offset {
                    when {
                        shouldReset -> resetAnimation
                        else -> IntOffset(0, currentOffset.roundToInt())
                    }
                }
                .draggable(
                    state = rememberDraggableState { delta -> currentOffset += delta },
                    orientation = Orientation.Vertical,
                    onDragStopped = {
                        shouldReset = true
                        currentOffset = 0F
                    }
                )
        ) {}
    }
}

You can define the offset as an Animatable .您可以将偏移量定义为Animatable
While dragging use the method snapTo to update the current value as the initial value and the onDragStopped to start the animation.拖动时使用方法snapTo将当前值更新为初始值,使用onDragStopped方法启动 animation。

val coroutineScope = rememberCoroutineScope()
val offsetY  =  remember { Animatable(0f) }

Box(contentAlignment = Alignment.TopCenter, modifier = Modifier.fillMaxSize()) {
    Surface(
        color = Color(0xFF34AB52),
        modifier = Modifier
            .size(100.dp)
            .offset {
                IntOffset(0, offsetY.value.roundToInt())
            }
            .draggable(
                state = rememberDraggableState { delta ->
                    coroutineScope.launch {
                        offsetY.snapTo(offsetY.value + delta)
                    }
                },
                orientation = Orientation.Vertical,
                onDragStopped = {
                    coroutineScope.launch {
                        offsetY.animateTo(
                            targetValue = 0f,
                            animationSpec = tween(
                                durationMillis = 3000,
                                delayMillis = 0
                            )
                        )
                    }
                }
            )
    ) {
    }
}

在此处输入图像描述

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

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