是否可以将 lottie 动画添加到 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:您或您的 View 必须在设置组合之前设置 Drawable.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) {
}
}
这会阻止异常发生,但图标不会绘制在工具栏中。
我如何使它工作?
问题是否与
LottieDrawable
的固有高度有关?Drawable.Callback
应该做什么(如果有的话)?Fragment
/Activity
生命周期有什么影响吗?即我应该在销毁时停止或清理某些东西吗?
最佳答案
我也有这个疑问,我留下了我的答案以防其他人需要它,我编写了这段代码并且它对我有用。
在 Activity 中创建一个属性:
private LottieDrawable animateCameraIcon;
并将此代码放入您的 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);
}
});
然后在方法 public boolean onCreateOptionsMenu(Menu menu) 中做这个:
if(animateCameraIcon != null){
MenuItem cameraMenuItem =menu.getItem(0);
cameraMenuItem.setIcon(animateCameraIcon);
}
关于android - 在Android工具栏中使用Lottie动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46644083/