android - 在 Jetpack Compose 中重置可拖动项目的偏移动画
问题描述
我有一个可以垂直拖动的绿色方块。但是每当我停止拖动它时,我希望它用动画将偏移量重置为开始。我试过这样,但我无法弄清楚。有人知道该怎么做吗?
@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
)
)
}
}
)
) {
}
}
推荐阅读
- javascript - 如何使用 javascript 从 Web 中的 Firebase 检索数据?
- javascript - 重新布线不导入本地目录
- flutter - 如何在 Flutter 上优雅地在我自己的类中实现 Shared_preferences?
- apache2 - Apache2:如何记录被拒绝的连接和客户端超时
- amazon-web-services - 查找最新的 AWS API 版本以锁定版本
- c - #包括
导致错误 - javascript - 使用循环构建对象数组
- unity3d - 有什么方法可以改变 Unity 中自定义 Sprite 的 FilterMode?
- typescript - 可以选择在打字稿中扩展一种类型的道具?
- javascript - 根据另一个数组获取一个数组中元素的索引