Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drag and drop then animation for going back (Jetpack compose 1.0.0-alpha07) : Thank you Joost Klitsie for your help on the Slack channel :)
@Preview
@Composable
fun DragAndDropComponent() {
Column(modifier = Modifier.size(300.dp).background(Color.Red)) {
val x = animatedFloat(150f)
val y = animatedFloat(150f)
val bouncySpring = SpringSpec(
dampingRatio = DampingRatioMediumBouncy,
stiffness = StiffnessLow,
visibilityThreshold = DefaultDisplacementThreshold)
val stiffSpring = SpringSpec(
dampingRatio = DampingRatioLowBouncy,
stiffness = StiffnessHigh,
visibilityThreshold = DefaultDisplacementThreshold)
Box(modifier = Modifier
.offset(
with(DensityAmbient.current) { x.value.toDp() },
with(DensityAmbient.current) { y.value.toDp() })
.size(10.dp)
.background(Color.Blue)
.dragGestureFilter(
object : DragObserver {
override fun onDrag(dragDistance: Offset): Offset {
x.animateTo(
targetValue = x.targetValue + dragDistance.x,
anim = stiffSpring
)
y.animateTo(
targetValue = y.targetValue + dragDistance.y,
anim = stiffSpring
)
return super.onDrag(dragDistance)
}
override fun onStop(velocity: Offset) {
super.onStop(velocity)
reset()
}
override fun onCancel() {
super.onCancel()
reset()
}
private fun reset() {
x.animateTo(
targetValue = 150f,
anim = bouncySpring)
y.animateTo(
targetValue = 150f,
anim = bouncySpring)
}
},
startDragImmediately = true
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment