Android SharedPreferences Tutorial and Example

Building a Custom Animated Progress Indicator

Feedback matters whenever an Android app waits for a network response, database query or file upload. A loading spinner signals active work, while a determinate bar shows how much of measurable work is complete.

Material supplies ready-made indicators, but a product may need its own shape, colour or motion. A small custom View gives Android developers control over the sweep angle, stroke and animation.

For Australian users, this feedback appears in Google Play apps tied to local services: Opal travel information in Sydney, Transport Victoria journeys in Melbourne, Woolworths or Coles click-and-collect, and Australia Post parcel tracking. Regional mobile coverage can be patchy, so the indicator must stay clear when completion takes longer than expected.

This Kotlin example provides determinate and indeterminate states, using a rounded Canvas arc and ValueAnimator for frame updates.

Start with the interaction goal

Choose the state from available information. Use determinate progress when the ratio is known, such as 0.5 for a half-finished upload. Use indeterminate progress when duration cannot be estimated, such as opening a route planner.

Let motion describe the operation. A rotating arc communicates active waiting, while a growing arc communicates measurable completion. Reserve its layout space so the surrounding screen does not jump when the state changes.

Build the drawing layer

Extend View for a simple canvas shape. Paint controls the stroke, rounded ends and colours, while onDraw positions the track. Fixed minimum dimensions prevent flexible parents from collapsing the indicator.

Define the visual values as Android resources so they can be changed for different themes:

<color name="progress_track">#1F000000</color>
<color name="progress_accent">#007A3E</color>
<dimen name="progress_stroke">8dp</dimen>

Keep the track quieter than the moving segment, but give both enough contrast for light and dark backgrounds. Store progress as a fraction from 0f to 1f and clamp incoming values.

Animate progress with ValueAnimator

ValueAnimator provides frame updates on the main thread. Use a decelerating curve for measured progress and a linear curve for a continuous spinner.

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat

class AnimatedProgressView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : View(context, attrs) {

    var isIndeterminate = false
        private set

    var progress = 0f
        set(value) {
            field = value.coerceIn(0f, 1f)
            invalidate()
        }

    private val track = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
    }

    private val indicator = Paint(track)
    private var animator: ValueAnimator? = null
    private var rotation = 0f

    init {
        track.color = ContextCompat.getColor(context, R.color.progress_track)
        indicator.color =
            ContextCompat.getColor(context, R.color.progress_accent)

        val stroke = resources.getDimension(R.dimen.progress_stroke)
        track.strokeWidth = stroke
        indicator.strokeWidth = stroke
    }

    fun animateProgressTo(value: Float) {
        isIndeterminate = false
        animator?.cancel()

        val target = value.coerceIn(0f, 1f)
        animator = ValueAnimator.ofFloat(progress, target).apply {
            duration = 650
            interpolator = DecelerateInterpolator()
            addUpdateListener {
                progress = it.animatedValue as Float
            }
            start()
        }
    }

    fun showIndeterminate() {
        isIndeterminate = true
        animator?.cancel()

        animator = ValueAnimator.ofFloat(0f, 360f).apply {
            duration = 1100
            repeatCount = ValueAnimator.INFINITE
            interpolator = LinearInterpolator()
            addUpdateListener {
                rotation = it.animatedValue as Float
                invalidate()
            }
            start()
        }
    }

    override fun onDraw(canvas: Canvas) {
        val size =
            (minOf(width, height) - track.strokeWidth).coerceAtLeast(0f)
        val left = (width - size) / 2f
        val top = (height - size) / 2f
        val right = left + size
        val bottom = top + size

        if (isIndeterminate) {
            canvas.save()
            canvas.rotate(rotation, width / 2f, height / 2f)
            canvas.drawArc(left, top, right, bottom, -90f, 100f, false, track)
            canvas.drawArc(left, top, right, bottom, -90f, 70f, false, indicator)
            canvas.restore()
        } else {
            canvas.drawArc(left, top, right, bottom, -90f, 360f, false, track)
            canvas.drawArc(
                left, top, right, bottom, -90f, 360f * progress, false, indicator
            )
        }
    }

    override fun onDetachedFromWindow() {
        animator?.cancel()
        animator = null
        super.onDetachedFromWindow()
    }
}

The determinate path animates only the changed fraction. The indeterminate path repeats a 360-degree rotation and draws a shorter moving arc, producing the familiar loading spinner effect. Keep the cycle between roughly 800 and 1200 milliseconds so the motion feels active without becoming distracting.

Callbacks can report downloaded bytes, completed database rows or processed records. Normalise those values before calling animateProgressTo, and use the indeterminate state only when no meaningful ratio exists.

Compare the available progress patterns

Standard widgets remain sensible when their motion already matches the design system. A custom view earns its extra code when the brand, geometry or state behaviour needs direct control.

Pattern Best suited to Main trade-off
Material linear indicator Known duration and familiar Android feedback Limited visual treatment
Material circular indicator Compact or indefinite waiting states Standard geometry
AnimatedProgressView Branded arcs and tailored motion The app owns accessibility and lifecycle behaviour
Static ProgressBar Simple pending status Provides no movement or percentage

Material components already handle common theming and accessibility conventions. The custom implementation must reproduce those responsibilities, particularly meaningful labels, range information and clean lifecycle handling.

Add the indicator to an Android screen

Place the class in the layout using its package name. A square shape keeps the arc centred as it rotates.

<com.example.progressdemo.AnimatedProgressView
    android:id="@+id/progress"
    android:layout_width="72dp"
    android:layout_height="72dp"
    android:contentDescription="@string/progress_status"
    android:visibility="gone" />

Expose progress updates from a ViewModel and deliver them on the main thread:

viewModel.refreshCatalog { fraction ->
    binding.progress.animateProgressTo(fraction)

    if (fraction >= 1f) {
        binding.progress.visibility = View.GONE
    }
}

Use View.GONE when the indicator has no meaningful space in the final layout, or View.INVISIBLE when hiding it would move nearby controls. A loading spinner does not replace an error message; retain the failed state and explain how the user can retry.

Handle accessibility, lifecycle and performance

The example cancels its animator when detached from the window. A production view should also pause animation while hidden and resume it when visible. Screen-scoped network calls and callbacks should follow the same lifecycle.

Add range information for determinate progress so TalkBack can report a percentage instead of treating the ring as decorative:

override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) {
    super.onInitializeAccessibilityNodeInfo(info)
    info.className = "android.widget.ProgressBar"

    if (!isIndeterminate) {
        info.rangeInfo = AccessibilityNodeInfo.RangeInfo.obtain(
            AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT,
            0f,
            1f,
            progress
        )
    }
}

Give the view a concise contentDescription that names the operation, such as “Loading parcel tracking”. Do not change it on every animation frame because repeated announcements make the screen difficult to use. Announce completion or a meaningful milestone instead.

Test on small phones, tablets and high-density displays, then repeat in dark mode and with system animations disabled. Reuse objects in onDraw, avoid a competing timer and keep the final state visible long enough to register. Used this way, the indicator becomes dependable feedback: it shows motion while waiting, reports measured completion and releases animation resources with the screen.