Last active
March 26, 2021 05:12
-
-
Save pranavjayaraj/16e59db734cdc11ec9ffd41bf0df84cc to your computer and use it in GitHub Desktop.
Jetpack animations
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 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good example! According to the guidelines,
@Composable
functions MUST be a noun and not a verb. In this example, instead ofSetupAnimationLayout()
andSetupAnimationButtons()
, you can useAnimationLayout()
andAnimationButton()
.