[英]Use Lottie animation in Android toolbar
是否可以在Android工具欄中添加lottie動畫?
我試過這個:
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
生命周期是否有任何影響? 即我應該停止或清理破壞的東西?
我也有這個疑問,我離開了我的答案以防其他人需要它,我制作這個代碼,它適用於我。
在活動中創建一個屬性:
private LottieDrawable animateCameraIcon;
: 並將此代碼放入您的活動 :
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);
}
});
make this: 在方法中, 使這個:
if(animateCameraIcon != null){
MenuItem cameraMenuItem =menu.getItem(0);
cameraMenuItem.setIcon(animateCameraIcon);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.