Dynamically replace Image in Lottie animation at runtime

LottieAnimationView extends an ImageView. In other words, the LottieAnimationView is also an ImageView.

So, you can set a image on LottieAnimationView the same way you set a image to a ImageView

For example:

if (isAnimated) {
    mLottieView.setAnimation("<json file name from asset folder>");
} else {
    mLottieView.setImageResource(R.drawable.square_image);
}

This is just an example about how you can use the same view to play an animation (json file) your just display an Image like any ImageView..


Lottie has one XML attribute app:lottie_imageAssetsFolder, which can also be set at run-time: animationView.setImageAssetsFolder("images/");. with that set, one can reference images in the json. this is documented in-line; see the comments above line #599 and #630. this is also explained in the documentation (src/assets might not be an option, since it is not writable):

Sometimes, you don't have the images bundled with the device. You may do this to save space in your apk or if you downloaded the animation from the network. To handle this case, you can set an ImageAssetDelegate on your LottieAnimationView or LottieDrawable. The delegate will be called every time Lottie tries to render an image. It will pass the image name and ask you to return the bitmap. If you don't have it yet (if it's still downloading, for example) then just return null and Lottie will continue to ask on every frame until you return a non-null value.

animationView.setImageAssetDelegate(new ImageAssetDelegate() {
    @Override
    public Bitmap fetchBitmap(LottieImageAsset asset) {
        if (downloadedBitmap == null) {
            // We don't have it yet. Lottie will keep asking until we return a non-null bitmap.
           return null;
        }
        return downloadedBitmap;
    }
});

Managed to do this: the problem was that my After Effects animation had a vector shape, and I was trying to replace this. After I changed the original animation to have a .png instead, I could replace the Image at runtime. Worked just fine.

// First I converted the png I wanted to see at runtime to a bitmap:

Bitmap bitmapImage = BitmapFactory.decodeResource(getResources(), R.drawable.imageBlah);

// I used the lambda: 

lottieAnimationView.setImageAssetDelegate( lottieImageAsset -> bitmapImage);

This worked for ONE image, now I'm going to see how about replacing multiple images at runtime.