4

是否可以将抽签动画添加到 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生命周期有什么影响吗?即我应该停止或清理破坏的东西吗?

4

1 回答 1

2

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

在活动中创建一个属性:

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);
}
于 2018-09-28T03:33:31.233 回答