I am using an animated vector drawable for an app that supports Android API 19-26. In order to restart the animation (it's a custom circular loading animation) I use AnimatedVectorDrawable.registerAnimationCallback, to restart the animation in the onAnimationEnd callback. This works great on API >= 23 and due to AnimatedVectorDrawableCompat it also works on API 19.
However, it doesn't work on API 21 and 22, because the class AnimatedVectorDrawable is already present in these APIs, but the registerAnimationCallback method was only added in API 23. How can I force devices that run API 21 or 22 to use AnimatedVectorDrawableCompat instead of their AnimatedVectorDrawable class, so that I can use registerAnimationCallback?
Here is the method I wrote for starting the animation for different API versions (It's in Kotlin):
private fun startAnimation() {
if (Build.VERSION.SDK_INT >= 23) {
((circular_progress.drawable as LayerDrawable)
.findDrawableByLayerId(R.id.loading_circle) as AnimatedVectorDrawable).apply {
registerAnimationCallback(@TargetApi(23)
object : Animatable2.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable?) {
super.onAnimationEnd(drawable)
this@apply.start()
}
override fun onAnimationStart(drawable: Drawable?) = super.onAnimationStart(drawable)
})
}.start()
} else if (Build.VERSION.SDK_INT >= 21) {
((circular_progress.drawable as LayerDrawable)
.findDrawableByLayerId(R.id.loading_circle) as AnimatedVectorDrawable).apply {
start()
// No registerAnimationCallback here =(
}
} else {
((circular_progress.drawable as LayerDrawable)
.findDrawableByLayerId(R.id.loading_circle) as AnimatedVectorDrawableCompat).apply {
registerAnimationCallback(object :
Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable?) {
super.onAnimationEnd(drawable)
this@apply.start()
}
override fun onAnimationStart(drawable: Drawable?) = super.onAnimationStart(drawable)
})
}.start()
}
}