我的动画代码崩溃了。它是从xml创建的动画:
<animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt">
//not relevant
</animated-vector>运行动画并崩溃的代码:
val animationDrawable = ContextCompat.getDrawable(context, R.drawable.anim_logbook_register_measurement)
val callback = object : Animatable2Compat.AnimationCallback() {
override fun onAnimationStart(drawable: Drawable?) {
super.onAnimationStart(drawable)
//not relevant
}
override fun onAnimationEnd(drawable: Drawable) {
//not relevant
}
}
AnimatedVectorDrawableCompat.registerAnimationCallback(animationDrawable, callback)
animationCallback = callback
(animationDrawable as? Animatable)?.start()AnimatedVectorDrawableCompat.registerAnimationCallback(animationDrawable, callback)行发生崩溃,原因如下:
android.graphics.drawable.AnimatedVectorDrawable cannot be cast to androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat看起来ContextCompat.getDrawable在android6上创建了非androidx的AnimatedVectorDrawable,而AnimatedVectorDrawableCompat .registerAnimationCallback期望androidx one并崩溃。当查看AnimatedVectorDrawableCompat内部时,这一点变得很明显
public static void registerAnimationCallback(Drawable dr,
Animatable2Compat.AnimationCallback callback) {
if (dr == null || callback == null) {
return;
}
if (!(dr instanceof Animatable)) {
return;
}
if (Build.VERSION.SDK_INT >= 24) {
registerPlatformCallback((AnimatedVectorDrawable) dr, callback);
} else {
((AnimatedVectorDrawableCompat) dr).registerAnimationCallback(callback);
}
} 在我看来,line的Android bug,有人注意到这一点吗?有没有一种方法可以在从5开始的所有版本上工作?
发布于 2020-01-16 00:06:27
这很糟糕,但如果我像这样从xml加载drawable,它显然是有效的:
val animationDrawable = return if (Build.VERSION.SDK_INT >= 24) {
ContextCompat.getDrawable(this, R.drawable.anim_logbook_register_measurement)
} else {
AnimatedVectorDrawableCompat.create(this, R.drawable.anim_logbook_register_measurement)
}https://stackoverflow.com/questions/59752902
复制相似问题