I have an animated vector drawable asset in my drawables folder. I use the following code to run it on button click
val myVectorDrawable = ResourcesCompat.getDrawable(
resources,
R.drawable.animation,
theme
)
button.setOnClickListener {
image.setImageDrawable(null)
image.setImageDrawable(myVectorDrawable)
val drawable = image.drawable
if (drawable is AnimatedVectorDrawableCompat) {
drawable.start()
} else if (drawable is AnimatedVectorDrawable)
drawable.start()
}
This runs perfectly if the device runs an android version > 24 and crashes otherwise. I need to support android devices with minimum SDK 21.
My questions are
- How to make my code support devices with
21up to24. - is there a better way to run
AnimatedVectorDrawableanimation
If you know you are using an animated vector, you can use
AnimatedVectorDrawableCompat.create()to create anAnimatedVectorDrawableCompatinstance that is available on all API 14+ devices:However, if you want a more generic approach, you must instead use
AppCompatResources.getDrawable()instead ofResourcesCompat.getDrawable()as that properly takes into account theVectorDrawableCompat,AnimatedVectorDrawableCompat, andAnimatedStateListDrawableCompatclasses in a way that is compatible with all API levels: