Created
March 17, 2024 22:02
-
-
Save yveskalume/74cb99fa7e25c5887796fd4c48c581d0 to your computer and use it in GitHub Desktop.
Shake animation for text field on wrong value submission
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
@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