Why Use Visibility Animations?
For example:
AnimatedVisibility(
visible = ,
enter = ,
exit =
) - visible: This is the boolean state that controls whether the composable should be shown (true) or hidden (false).
- enter: Specifies the animation that plays when the composable becomes visible.
- exit: Specifies the animation that plays when the composable becomes invisible.
Types of Visibility Animations
- Fade In / Fade Out: This makes composables gradually appear or disappear by adjusting their opacity.
- Expand / Shrink: These transitions animate changes in size, creating a sense of "growing" into the view or "shrinking" out of it.
- Custom Animations: You can combine multiple animations for more complex transitions, like fading in while expanding.
Example:
package com.example.myapplication
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandIn
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun VisibilityAnimation() {
var isVisible by remember { mutableStateOf(true) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Combined animation for fade in + expand and fade out + shrink
AnimatedVisibility(
visible = isVisible,
enter = fadeIn() + expandIn(), // Fade in and expand
exit = fadeOut() + shrinkOut() // Fade out and shrink
) {
Text(text = "I am animated with multiple effects!")
}
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { isVisible = !isVisible }) {
Text(if (isVisible) "Hide" else "Show")
}
}
}
