Skip to content

Instantly share code, notes, and snippets.

@pranavjayaraj
Last active March 26, 2021 05:12
Show Gist options
  • Save pranavjayaraj/16e59db734cdc11ec9ffd41bf0df84cc to your computer and use it in GitHub Desktop.
Save pranavjayaraj/16e59db734cdc11ec9ffd41bf0df84cc to your computer and use it in GitHub Desktop.
Jetpack animations
@Composable
fun AnimationLayout() {
var state by remember { mutableStateOf(false) }
var animSpec by remember { mutableStateOf("snap") }
val startColor = Color.Blue
val endColor = Color.Green
val backgroundColor by animateColorAsState(
if (state) endColor else startColor,
getAnimationSpec(animSpec)
)
Column(
modifier = Modifier.fillMaxSize().background(backgroundColor),
verticalArrangement = Arrangement.Center
) {
AnimationButtons(onValueChanged = { currState, animName ->
animSpec = animName
state = currState
}, state = state)
}
}
@Composable
fun AnimationButtons(onValueChanged: (Boolean, String) -> Unit, state: Boolean) {
for (anim in animationSpec.values()) {
Button(
onClick = { onValueChanged(!state, anim.value) },
modifier = Modifier.height(50.dp).width(100.dp).padding(top = 10.dp),
content = {
Text(text = anim.value, color = Color.White)
})
}
}
fun getAnimationSpec(spec: String): AnimationSpec<Color> {
return when (spec) {
animationSpec.SPRING.value -> {
spring(
dampingRatio = Spring.DampingRatioHighBouncy,
stiffness = Spring.StiffnessMedium
)
}
animationSpec.TWEEN.value -> {
tween(
durationMillis = 2000,
delayMillis = 500,
easing = LinearOutSlowInEasing
)
}
animationSpec.REPEATABLE.value -> {
repeatable(
iterations = 3,
animation = tween(durationMillis = 200),
repeatMode = RepeatMode.Reverse
)
}
animationSpec.INFINITE_REPEATABLE.value -> {
infiniteRepeatable(
animation = tween(durationMillis = 200),
repeatMode = RepeatMode.Reverse
)
}
else -> {
snap(delayMillis = 40)
}
}
}
@vishnuharidas
Copy link

vishnuharidas commented Mar 24, 2021

Good example! According to the guidelines, @Composable functions MUST be a noun and not a verb. In this example, instead of SetupAnimationLayout() and SetupAnimationButtons(), you can use AnimationLayout() and AnimationButton().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment