This is my build.gradle
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 26
vectorDrawables.useSupportLibrary = true
}
and a part of the layout
<ImageView
android:id="@+id/recents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:scaleType="fitCenter"
app:srcCompat="@drawable/anim_test"/>
and the class cast:
val np = convertView.findViewById<ImageView>(R.id.recents)
val anim = np.drawable as AnimatedVectorDrawableCompat
This works as expected on Lolipop (sdk 21) but fails on Nougat saying:
android.graphics.drawable.AnimatedVectorDrawable cannot be cast to android.support.graphics.drawable.AnimatedVectorDrawableCompat
What I dont get is, why does it return an AnimatedVectorDrawableCompat on sdk level 21 at all when AnimatedVectorDrawable is already supported by the system. And why does it return the AnimatedVectorDrawable in Nougat in spite of specifying vectorDrawables.useSupportLibrary = true
.
Short answer:
Use
AnimatedVectorDrawableCompat.registerAnimationCallback
static method and it will do the job for you.Long answer:
I was having the same problem when I was trying to loop an animated vector drawable. Until I found out the support library returns different classes (
AnimatedVectorDrawable
andAnimatedVectorDrawableCompat
) on different SDK levels.It was not documented anywhere except this wonderful blog post of Nick Butcher:
https://medium.com/androiddevelopers/re-animation-7869722af206
He says:
In the blog post the author also suggests other methods to work around this issue like using
AnimatedVectorDrawableCompat#create
method and setting the drawable in the runtime.I recommend you to read the whole article.
Hope this helps.