【问题标题】:Use Lottie animation in Android toolbar在 Android 工具栏中使用 Lottie 动画
【发布时间】:2018-09-28 15:07:18
【问题描述】:

是否可以在 Android 工具栏上添加抽签动画?

我试过这个:

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
    })
}

这会导致IllegalStateException: You or your view must set a Drawable.Callback before setting the composition.

所以我添加了一个回调:

 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) {
            }

        }

这会阻止异常发生,但图标未绘制在工具栏中。

我该如何进行这项工作?

  • 问题是否与LottieDrawable 的固有高度有关?

  • Drawable.Callback 应该做什么(如果有的话)?

  • Fragment/Activity 生命周期有什么影响吗?即我应该停止或清理破坏的东西吗?

【问题讨论】:

标签: android kotlin android-toolbar lottie


【解决方案1】:

我也有这个疑问,我留下了答案以防其他人需要它,我编写了这段代码,它对我有用。

在activity中创建一个属性:

private LottieDrawable animateCameraIcon;

并将此代码放入您的活动中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);
   }
});

public boolean onCreateOptionsMenu(Menu menu) 方法中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2015-02-04
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多