Created
August 29, 2024 16:36
-
-
Save sajjadyousefnia/f21a42f1ed7c8e47a7d17adc3ef96747 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun Modifier.animatePlacement(): Modifier = composed { | |
val scope = rememberCoroutineScope() | |
var targetOffset by remember { mutableStateOf(IntOffset.Zero) } | |
var animatable by remember { | |
mutableStateOf<Animatable<IntOffset, AnimationVector2D>?>(null) | |
} | |
this | |
// 🔥 onPlaced should be before offset Modifier | |
.onPlaced { | |
// Calculate the position in the parent layout | |
targetOffset = it | |
.positionInParent() | |
.round() | |
} | |
.offset { | |
// Animate to the new target offset when alignment changes. | |
val anim = animatable ?: Animatable(targetOffset, IntOffset.VectorConverter).also { | |
animatable = it | |
} | |
if (anim.targetValue != targetOffset) { | |
scope.launch { | |
anim.animateTo(targetOffset, spring(stiffness = Spring.StiffnessMediumLow)) | |
} | |
} | |
// Offset the child in the opposite direction to the targetOffset, and slowly catch | |
// up to zero offset via an animation to achieve an overall animated movement. | |
animatable?.let { it.value - targetOffset } ?: IntOffset.Zero | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment