Skip to content

Instantly share code, notes, and snippets.

@loloof64
Last active December 17, 2020 01:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loloof64/31bbb7af98df85918f67a1a48046a80f to your computer and use it in GitHub Desktop.
Save loloof64/31bbb7af98df85918f67a1a48046a80f to your computer and use it in GitHub Desktop.
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