Created
February 18, 2025 17:28
-
-
Save cavin-macwan/ecb6f531deee97cb927d86761c087c18 to your computer and use it in GitHub Desktop.
Shake Animation Implementation (useful for error states)
This file contains hidden or 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
/** | |
* ``` | |
* @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