Thracian
Thracian

Reputation: 67039

implement a spinning activity indicator with Jetpack Compose

This is a share your knowledge, Q&A-style inspired by this question on Reddit and the one linked to stackoverflow

Result is

enter image description here

Upvotes: 4

Views: 1555

Answers (1)

Thracian
Thracian

Reputation: 67039

This is just a sample to show to build spinning progress indicator. Item count(8 or 12), animation duration, spinning item color or color of static items can be customized based on preference.

@Composable
private fun SpinningProgressBar(modifier: Modifier = Modifier) {

    val count = 12

    val infiniteTransition = rememberInfiniteTransition()
    val angle by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = count.toFloat(),
        animationSpec = infiniteRepeatable(
            animation = tween(count * 80, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    )

    Canvas(modifier = modifier.size(48.dp)) {

        val canvasWidth = size.width
        val canvasHeight = size.height

        val width = size.width * .3f
        val height = size.height / 8

        val cornerRadius = width.coerceAtMost(height) / 2

        for (i in 0..360 step 360 / count) {
            rotate(i.toFloat()) {
                drawRoundRect(
                    color = Color.LightGray.copy(alpha = .7f),
                    topLeft = Offset(canvasWidth - width, (canvasHeight - height) / 2),
                    size = Size(width, height),
                    cornerRadius = CornerRadius(cornerRadius, cornerRadius)
                )
            }
        }

        val coefficient = 360f / count

        for (i in 1..4) {
            rotate((angle.toInt() + i) * coefficient) {
                drawRoundRect(
                    color = Color.Gray.copy(alpha = (0.2f + 0.2f * i).coerceIn(0f, 1f)),
                    topLeft = Offset(canvasWidth - width, (canvasHeight - height) / 2),
                    size = Size(width, height),
                    cornerRadius = CornerRadius(cornerRadius, cornerRadius)
                )
            }
        }
    }
}

I created a library that contains other type of Spinners as can be seen in gif below is available here

enter image description here

Upvotes: 11

Related Questions