Android SharedPreferences Tutorial and Example

Animating Android interfaces with ValueAnimator

ValueAnimator is Android’s timing engine for turning a starting value into an ending value over a defined period. It calculates intermediate values such as 0.0, 0.25, and 0.75, giving developers control over opacity, position, colour channels, and custom model properties. The target view does not move by itself; an update listener decides what each calculated value means.

That distinction makes the class useful for more than a simple fade. One progress value can drive several properties, interpolate data between business states, or produce an effect that cannot be expressed cleanly as a fixed view transition. ValueAnimator is also the foundation beneath ObjectAnimator, although the base class is the better starting point when explicit control matters.

For an app used by commuters in Sydney and Melbourne, a restrained reveal can make a disruption banner easier to notice without delaying its message. The interface must remain understandable when a train enters a tunnel or a regional connection becomes slow, so motion should improve orientation rather than become a prerequisite for reading essential information.

The Kotlin examples below use ViewBinding and the Australian spelling “colour” where relevant. Australian product teams commonly display prices in AUD with GST included, format dates as day/month/year, and use informal internal shorthand such as “arvo”; customer-facing screens can retain a friendly local voice without letting it compete with the animation itself.

What ValueAnimator actually controls

ValueAnimator belongs to Android’s property animation framework. It operates on values, whereas ObjectAnimator knows how to assign a particular property on a target object, and ViewPropertyAnimator offers concise methods for common view changes. The right abstraction keeps update logic clear.

Capability ValueAnimator ObjectAnimator ViewPropertyAnimator
Core behaviour Calculates changing values Calculates and assigns object properties Animates common View properties
Typical use Custom or multi-property motion Fade or translate one target property Quick fades, moves, and scaling
Control level You read values and apply them Target and property are declared Chainable calls on a View
Best fit Flexible data-driven effects Concise property animation Simple interface transitions

For a tutorial focused on the mechanism, start with ValueAnimator and map its output yourself. Later, ObjectAnimator can shorten code for one known property; a custom evaluator remains useful when several values must advance together or when the animated data is not a View.

Building a simple value animation

Suppose a promotional card should begin slightly transparent and 32 pixels below its resting position. A single float can represent that reveal, keeping both visual properties synchronised.

binding.promoCard.alpha = 0f
binding.promoCard.translationY = 32f

val reveal = ValueAnimator.ofFloat(0f, 1f).apply {
    duration = 450L

    addUpdateListener { animation ->
        val progress = animation.animatedValue as Float
        binding.promoCard.alpha = progress
        binding.promoCard.translationY = (1f - progress) * 32f
    }
}

reveal.start()

The listener receives the running animator and reads animatedValue, which holds the current Float. ValueAnimator does not assign alpha or translation automatically. Applying the result inside the listener gives you complete control and makes the animation easy to extend with rotation, scale, or a custom calculation.

For visual inspiration while refining the card’s spacing and hierarchy, take a look at Flat Elements. Keep the movement small enough that users can still scan nearby content, especially in a crowded transport app where another notification may arrive.

Configuring timing and repetition

Timing controls how the generated values are distributed. Duration defines the length, an interpolator shapes the easing curve, and repeat settings determine whether the animation loops. LinearOutSlowIn and similar curves feel natural for entrances because they begin gently and settle more slowly.

<?xml version="1.0" encoding="utf-8"?>
<valueAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="900"
    android:interpolator="@android:interpolator/fast_out_slow_in"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:valueType="floatType"
    android:values="0.98,1.0" />

Place the resource in res/animator rather than res/anim. The animator folder holds property animators, while the traditional anim folder contains view animations with a different XML model. Loading the definition and attaching the update listener keeps reusable timing separate from the screen that displays it.

val pulse = AnimatorInflater.loadAnimator(
    context,
    R.animator.card_pulse
) as ValueAnimator

pulse.addUpdateListener { animation ->
    val scale = animation.animatedValue as Float
    binding.promoCard.scaleX = scale
    binding.promoCard.scaleY = scale
}

pulse.start()

REVERSE alternates between the declared values, producing a pulse that returns to its origin. RESTART jumps back to the starting value before repeating. For a busy screen, use INFINITE sparingly: a looping animation draws attention even when the underlying state has not changed.

Coordinating multiple animations

A single effect often needs a coordinated sequence. AnimatorSet can run several ValueAnimator instances together, start them in order, or nest one set inside another. This keeps timing relationships explicit without relying on unrelated coroutine delays or thread sleeps.

binding.statusCard.alpha = 0f
binding.statusCard.translationY = 24f

val fade = ValueAnimator.ofFloat(0f, 1f).apply {
    duration = 320L
    addUpdateListener { animation ->
        binding.statusCard.alpha = animation.animatedValue as Float
    }
}

val settle = ValueAnimator.ofFloat(24f, 0f).apply {
    duration = 320L
    addUpdateListener { animation ->
        binding.statusCard.translationY = animation.animatedValue as Float
    }
}

AnimatorSet().apply {
    playTogether(fade, settle)
    start()
}

The code uses one value for opacity and another for vertical settling, then plays both together. ObjectAnimator can compress the equivalent fade or translation into a shorter declaration, but ValueAnimator remains valuable when the same progress must influence several targets or when an update also changes application state.

Use AnimatorListenerAdapter for start, end, and cancellation callbacks. For example, a completion callback can unlock a button after a panel finishes expanding. Avoid using the callback as proof that content is usable; if animation settings remove motion, set the final layout immediately.

Handling lifecycle and accessibility

Production behaviour starts with lifecycle management. Keep a reference to a long-running animator and cancel it when its Activity or Fragment is destroyed; otherwise, an infinite loop can retain the host through its listener. Recreate short animations when the relevant screen returns instead of attempting to resume an old instance whose targets may no longer exist.

private val bannerAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
    duration = 400L

    addUpdateListener { animation ->
        val progress = animation.animatedValue as Float
        binding.statusCard.alpha = progress
        binding.statusCard.translationY = (1f - progress) * 32f
    }
}

override fun onDestroy() {
    bannerAnimator.cancel()
    super.onDestroy()
}

On Android 8.0 and later, ValueAnimator.areAnimatorsEnabled() reflects whether system animation is disabled. The sample applies the final position immediately in that case, so accessibility preferences do not leave the banner partly hidden. Motion should never be the only way to communicate a state change.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
    !ValueAnimator.areAnimatorsEnabled()
) {
    binding.statusCard.alpha = 1f
    binding.statusCard.translationY = 0f
} else {
    bannerAnimator.start()
}

For smooth rendering, prefer alpha, scale, rotation, and translation over repeatedly changing measured width or height, which can trigger layout work on every frame. On slower regional mobile networks, defer decorative motion until the essential message is available. Use a TypeEvaluator or ArgbEvaluator when the animated value represents colour or business data, producing motion that remains quick, accessible, and useful as the screen or connection changes.