Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
animate objext on x axis for shake effect
@Composable
fun Greeting(name: String) {
val coroutineScope = rememberCoroutineScope()
val view = LocalView.current
val offsetX = remember { Animatable(0f) }
Text(
text = "Hello $name!",
modifier = Modifier
.offset(offsetX.value.dp, 0.dp)
)
Button(onClick = { animateText(offsetX, coroutineScope, view) }) {
Text(text = "Animate")
}
}
private val shakeKeyframes: AnimationSpec<Float> = keyframes {
durationMillis = 800
val easing = FastOutLinearInEasing
// generate 8 keyframes
for (i in 1..8) {
val x = when (i % 3) {
0 -> 4f
1 -> -4f
else -> 0f
}
x at durationMillis / 10 * i with easing
}
}
private fun animateText(
offset: Animatable<Float, AnimationVector1D>,
coroutineScope: CoroutineScope,
view: View? = null,
) {
coroutineScope.launch {
offset.animateTo(
targetValue = 0f,
animationSpec = shakeKeyframes,
)
}
view?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.REJECT)
} else {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment