Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tutosrive/lottie-kt-test/llms.txt

Use this file to discover all available pages before exploring further.

A common requirement in animation-heavy apps is the ability to swap between different Lottie JSON files without restarting the activity. This demo implements a straightforward toggle pattern: a single Change button cycles between wh.json and logo2.json by tracking the current animation name in a local variable and reassigning it on each tap.

Button Click Handler

The complete click listener from MainActivity.kt:
MainActivity.kt
btnChange.setOnClickListener { viewModelStore ->
    anim = when (anim) {
        "wh.json" -> "logo2.json"
        "logo2.json" -> "wh.json"
        else -> "wh.json"
    }
    lottieView.setAnimation(anim)
    lottieView.frame = 0
    lottieView.playAnimation()
}

How It Works

The when Toggle Expression

The when expression evaluates the current value of anim and returns the next animation filename:
  • If anim is "wh.json", it switches to "logo2.json".
  • If anim is "logo2.json", it switches back to "wh.json".
  • The else branch guards against any unexpected state by defaulting back to "wh.json".
The result is immediately assigned back to anim, so successive taps continue alternating correctly.

Why lottieView.frame = 0 Is Needed

After calling setAnimation() with a new file, the LottieAnimationView has loaded the new composition but the internal frame counter still holds whatever position the previous animation stopped at. Setting lottieView.frame = 0 explicitly resets the playhead to the very first frame of the new animation before playAnimation() is called. Without this reset, the new animation would start partway through — or not appear to start at all if the frame counter exceeds the new composition’s total frame count.

Sequence of Calls

The three calls must happen in this order:
1

setAnimation(anim)

Loads and parses the new Lottie JSON composition from the assets/ directory. This replaces the previously loaded composition in memory.
2

frame = 0

Resets the playhead to frame zero so playback begins from the start of the new composition.
3

playAnimation()

Starts the animation loop. Because lottie_loop="true" is set in XML, it will repeat indefinitely until the next button tap.
In a real app with more than two animations, store the animation filenames in a list and keep an index instead of using a when expression. Increment the index on each tap (wrapping with % list.size) and read the current filename from the list — this scales to any number of animations without adding more branches.

Next, learn how to replace embedded images inside a Lottie JSON with your own Android drawables: Image Asset Delegation

Build docs developers (and LLMs) love