Skip to content

Instantly share code, notes, and snippets.

@yveskalume
Created March 17, 2024 22:02
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 yveskalume/74cb99fa7e25c5887796fd4c48c581d0 to your computer and use it in GitHub Desktop.
Save yveskalume/74cb99fa7e25c5887796fd4c48c581d0 to your computer and use it in GitHub Desktop.
Shake animation for text field on wrong value submission
@Composable
fun TextFieldScreen() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically)
) {
val context = LocalContext.current
val (email, onEmailChange) = remember {
mutableStateOf("")
}
val shakeAnimation = remember { Animatable(0f) }
var isError by remember {
mutableStateOf(false)
}
val coroutineScope = rememberCoroutineScope()
Column {
OutlinedTextField(
value = email,
isError = isError,
onValueChange = onEmailChange,
label = {
Text(text = "Email Address")
},
modifier = Modifier
.offset { IntOffset(shakeAnimation.value.roundToInt(), y = 0) }
.graphicsLayer {
translationX = shakeAnimation.value * 2
}
)
AnimatedVisibility(visible = isError, modifier = Modifier.align(Alignment.Start)) {
Text(text = "Invalid email address", color = MaterialTheme.colorScheme.error)
}
}
Button(onClick = {
if (email.isEmail()) {
onEmailChange("")
Toast.makeText(context, email, Toast.LENGTH_SHORT).show()
} else {
isError = true
coroutineScope.launch {
for (i in 0..10) {
when (i % 2) {
0 -> shakeAnimation.animateTo(5f, spring(stiffness = 100_000f))
else -> shakeAnimation.animateTo(-5f, spring(stiffness = 100_000f))
}
}
shakeAnimation.animateTo(0f)
}
}
}) {
Text(text = "Submit")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment