alexbirkett
alexbirkett

Reputation: 2682

Use Lottie animation in Android toolbar

Is it possible to add a lottie animation to an Android toolbar?

I attempted this:

override fun onCreateOptionsMenu(menu : Menu, inflater : MenuInflater) {
    inflater.inflate(R.menu.menu_program_fragment, menu)
    val menuFavorite = menu.findItem(R.id.menuSubscribe)
    val lottieDrawable =  LottieDrawable()
    LottieComposition.Factory.fromAssetFileName(activity, "favorite.json", {
        composition ->
        lottieDrawable.setComposition(composition)
        lottieDrawable.loop(true)
        lottieDrawable.playAnimation()
        lottieDrawable.invalidateSelf()
        menuFavorite.icon = lottieDrawable
    })
}

This results in a IllegalStateException: You or your view must set a Drawable.Callback before setting the composition.

So I added a callback:

 lottieDrawable.callback = object : Drawable.Callback {
            override fun unscheduleDrawable(who: Drawable?, what: Runnable?) {
            }

            override fun invalidateDrawable(who: Drawable?) {
             }

            override fun scheduleDrawable(who: Drawable?, what: Runnable?, `when`: Long) {
            }

        }

Which stops the exception occurring but the icon is not drawn in the toolbar.

How do I make this work?

Upvotes: 4

Views: 3028

Answers (1)

Roberto
Roberto

Reputation: 169

I also had that doubt and I left my answer in case someone else needed it, I make this code and it works for me.

Create an attribute in the activity:

private LottieDrawable animateCameraIcon;

and put this code in your activity protected void onCreate(Bundle savedInstanceState):

LottieTask<LottieComposition> task = LottieCompositionFactory.fromRawRes(this, R.raw.camera);

task.addListener(new LottieListener<LottieComposition>() {
    @Override
    public void onResult(LottieComposition result) {
        Log.i(TAG, "Loaded camera animation: "+result);
        animateCameraIcon = new LottieDrawable();
        animateCameraIcon.setComposition(result);
        animateCameraIcon.setRepeatCount(LottieDrawable.INFINITE);
        animateCameraIcon.setScale(0.23f);
        animateCameraIcon.playAnimation();
        animateCameraIcon.setSpeed(0.7f);
    }
});

task.addFailureListener(new LottieListener<Throwable>() {
   @Override
   public void onResult(Throwable result) {
      Log.e(TAG, "Error loading camera animation: "+result);
   }
});

And in the method public boolean onCreateOptionsMenu(Menu menu) make this:

if(animateCameraIcon != null){
  MenuItem cameraMenuItem =menu.getItem(0);
  cameraMenuItem.setIcon(animateCameraIcon);
}

Upvotes: 3

Related Questions