Last active
October 14, 2024 16:40
-
-
Save stevdza-san/ad7da2a5e76bde814888a78372e6e216 to your computer and use it in GitHub Desktop.
Loading Animation with Jetpack Compose
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
import androidx.compose.animation.core.* | |
import androidx.compose.foundation.background | |
import androidx.compose.foundation.layout.* | |
import androidx.compose.foundation.shape.CircleShape | |
import androidx.compose.material.MaterialTheme | |
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.LaunchedEffect | |
import androidx.compose.runtime.remember | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.graphics.graphicsLayer | |
import androidx.compose.ui.platform.LocalDensity | |
import androidx.compose.ui.unit.Dp | |
import androidx.compose.ui.unit.dp | |
import kotlinx.coroutines.delay | |
@Composable | |
fun LoadingAnimation( | |
modifier: Modifier = Modifier, | |
circleSize: Dp = 25.dp, | |
circleColor: Color = MaterialTheme.colors.primary, | |
spaceBetween: Dp = 10.dp, | |
travelDistance: Dp = 20.dp | |
) { | |
val circles = listOf( | |
remember { Animatable(initialValue = 0f) }, | |
remember { Animatable(initialValue = 0f) }, | |
remember { Animatable(initialValue = 0f) } | |
) | |
circles.forEachIndexed { index, animatable -> | |
LaunchedEffect(key1 = animatable) { | |
delay(index * 100L) | |
animatable.animateTo( | |
targetValue = 1f, | |
animationSpec = infiniteRepeatable( | |
animation = keyframes { | |
durationMillis = 1200 | |
0.0f at 0 with LinearOutSlowInEasing | |
1.0f at 300 with LinearOutSlowInEasing | |
0.0f at 600 with LinearOutSlowInEasing | |
0.0f at 1200 with LinearOutSlowInEasing | |
}, | |
repeatMode = RepeatMode.Restart | |
) | |
) | |
} | |
} | |
val circleValues = circles.map { it.value } | |
val distance = with(LocalDensity.current) { travelDistance.toPx() } | |
Row( | |
modifier = modifier, | |
horizontalArrangement = Arrangement.spacedBy(spaceBetween) | |
) { | |
circleValues.forEach { value -> | |
Box( | |
modifier = Modifier | |
.size(circleSize) | |
.graphicsLayer { | |
translationY = -value * distance | |
} | |
.background( | |
color = circleColor, | |
shape = CircleShape | |
) | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment