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

  • Accompanist placeholder api is deprecated. You can use the following structure instead.

    @Composable
    fun ShimmerEffectBox(
        modifier: Modifier = Modifier, isShow: Boolean = true,
        content: @Composable BoxScope.() -> Unit
    ) {
        val shimmerColors = listOf(
            Color.LightGray.copy(alpha = 0.6f),
            Color.LightGray.copy(alpha = 0.2f),
            Color.LightGray.copy(alpha = 0.6f)
        )
    
        val transition = rememberInfiniteTransition(label = "")
        val translateAnim by transition.animateFloat(
            initialValue = 0f, targetValue = 1000f, animationSpec = infiniteRepeatable(
                animation = tween(durationMillis = 1700, delayMillis = 200),
                repeatMode = RepeatMode.Restart
            ), label = ""
        )
    
        val brush = Brush.linearGradient(
            colors = shimmerColors,
            start = Offset.Zero,
            end = Offset(x = translateAnim, y = translateAnim)
        )
    
    
        if (isShow) {
            Box(
                modifier = modifier.background(brush)
            ) {
                Box(modifier = Modifier
                    .matchParentSize()
                    .graphicsLayer { alpha = 1f })
            }
        } else {
            Box(
                modifier = modifier
            ) {
                content()
            }
    
        }
    }
    

    Usage:

      Row {
                ShimmerEffectBox(
                    modifier = Modifier
                        .height(100.dp)
                        .padding(4.dp)
                        .weight(0.3f)
                        .clip(RoundedCornerShape(4.dp)),
                    isShow = true
                ) {
    
                    Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "")
                }
                ShimmerEffectBox(
                    modifier = Modifier
                        .height(100.dp)
                        .padding(4.dp)
                        .weight(0.7f)
                        .clip(RoundedCornerShape(4.dp)),
                    isShow = true
                ) {
    
                    Text(
                        text = "Content to display after content has loaded"
                    )
                }
            }