androidkotlinanimationandroid-jetpack-compose

Shimmer/Skeleton animation in Android Jetpack Compose


How can I create an animation like this to represent objects that are loading, thanks to everyone. Shimmer example

I looked for the whole day but the information that I found was in views, if anyone knows a dependency or how to create this I will be thankful.


Solution

  • The shimmer code works well, but it has a major recomposition issue. Here, I’ve optimized it using drawBehind to improve performance.

    @Composable
    fun Modifier.shimmerLoading(
        durationMillis: Int = 1000,
    ): Modifier {
        val transition = rememberInfiniteTransition(label = "")
    
        val translateAnimation by transition.animateFloat(
            initialValue = 0f,
            targetValue = 500f,
            animationSpec = infiniteRepeatable(
                animation = tween(
                    durationMillis = durationMillis,
                    easing = LinearEasing,
                ),
                repeatMode = RepeatMode.Restart,
            ),
            label = "",
        )
    
        return drawBehind {
            drawRect(
                brush = Brush.linearGradient(
                    colors = persistentListOf(
                        Color.LightGray.copy(alpha = 0.2f),
                        Color.LightGray.copy(alpha = 1.0f),
                        Color.LightGray.copy(alpha = 0.2f),
                    ),
                    start = Offset(x = translateAnimation, y = translateAnimation),
                    end = Offset(x = translateAnimation + 100f, y = translateAnimation + 100f),
                )
            )
        }
    }
    

    Using this is straightforward — just call it to the Modifier of your composable.

    Box(
        modifier = Modifier
            .size(80.dp)
            .clip(CircleShape)
            .shimmerLoading()
    )
    

    I highly recommend checking out this Medium article titled: "Shimmer Animation in Jetpack Compose Without Recomposition" about creating a shimmer effect with no recomposition and optimized performance. It’s packed with great tips!