Skip to content

Instantly share code, notes, and snippets.

@cavin-macwan
Created February 18, 2025 17:28
Show Gist options
  • Save cavin-macwan/ecb6f531deee97cb927d86761c087c18 to your computer and use it in GitHub Desktop.
Save cavin-macwan/ecb6f531deee97cb927d86761c087c18 to your computer and use it in GitHub Desktop.
Shake Animation Implementation (useful for error states)
/**
* ```
* @Composable
* fun ShakeScreen() {
* var shake by remember { mutableStateOf(false) }
* val interactionSource = remember { MutableInteractionSource() }
*
* Box(
* contentAlignment = Alignment.Center,
* modifier = Modifier.fillMaxSize()
* ) {
* ShakeContent(shake) {
* Text(
* text = "Tap here to shake it \uD83D\uDE09",
* modifier = Modifier.clickable(
* interactionSource = interactionSource,
* indication = null
* ) {
* shake = !shake
* }
* )
* }
* }
* }
*```
* */
@Composable
fun ShakeContent(
shake: Boolean,
content: @Composable () -> Unit
) {
val offsetX by animateFloatAsState(
targetValue = if (shake) 0f else 20f,
animationSpec = repeatable(
iterations = 3,
animation = tween(durationMillis = 50),
repeatMode = RepeatMode.Reverse
)
)
Box(
modifier = Modifier.offset {
IntOffset(offsetX.toInt(), 0)
}
) {
content()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment