我的动画代码崩溃了。这是从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
看起来像Android 6上的ContextCompat.getDrawable
会创建非androidx的AnimatedVectorDrawable
,而AnimatedVectorDrawableCompat .registerAnimationCallback
则期望androidx的一个并崩溃。在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);
}
}
[在我看来是Android的bug,有人知道吗?是否有一种方法可以在所有5以后的版本中使用?
我已经通过添加新的依赖关系解决了这个问题:
implementation "androidx.vectordrawable:vectordrawable:1.1.0"
implementation "androidx.vectordrawable:vectordrawable-animated:1.1.0"
并更改了我从xml加载动画的方式:
val animationDrawable = AnimatedVectorDrawableCompat.create(context, R.drawable.anim_logbook_register_measurement)