gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:53:03 27 4
gpt4 key购买 nike

我有一个可以垂直拖动的绿色方 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com