android - 在 Jetpack Compose 中重置可拖动项目的偏移动画

标签 android kotlin animation drag android-jetpack-compose

我有一个可以垂直拖动的绿色方 block 。但是每当我停止拖动它时,我希望它用动画将偏移量重置为开始。我试过这样,但我无法弄清楚。有人知道怎么做吗?

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

最佳答案

您可以将偏移量定义为 Animatable .
拖动时使用方法 snapTo 将当前值更新为初始值,使用 onDragStopped 方法开始动画。

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

enter image description here

关于android - 在 Jetpack Compose 中重置可拖动项目的偏移动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67304561/

相关文章:

android - 如何在圆形 ImageView 周围绘制边框?

java - proto buffer 的局限性——加载部分数据和共享字符串

android - 如何在 Android Studio 中将列表字段返回为空列表 "[]"?

android - 如何在 Jetpack Compose 中做 Multiline 芯片组?

javascript - 水平导航滑出有生长效果

android - 什么是android音轨的最大和最小值,音频类型为float?

kotlin - Intellij 中的 Kotlin 模块

javascript - 当我使用 JavaScript 更改类时,为什么 CSS 没有动画?

javascript - 无法理解这个 svg 动画

安卓异步任务 : start new Activity in onPostExecute()