AnimatedVectorDrawable支持<24

问题描述

我的drawables文件夹中有一个动画矢量可绘制资产。我使用以下代码在单击按钮时运行它

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()

        }

如果设备运行的是android版本> 24,则此命令运行正常,否则崩溃。我需要使用最低SDK 21来支持android设备。

我的问题是

  1. 如何使我的代码支持2124的设备。
  2. 是否有更好的方式来运行AnimatedVectorDrawable动画

解决方法

如果您知道自己正在使用动画矢量,则可以使用AnimatedVectorDrawableCompat.create()创建一个AnimatedVectorDrawableCompat实例,该实例在所有API 14+设备上都可用:

val drawable = AnimatedVectorDrawableCompat.create(
    this,// your Context
    R.drawable.animation)

button.setOnClickListener {
    image.setImageDrawable(null)
    image.setImageDrawable(drawable)

    drawable.start()
}

但是,如果您想要更通用的方法,则必须改用ResourcesCompat.getDrawable()VectorDrawableCompat和{ {1}}类与所有API级别兼容:

AnimatedVectorDrawableCompat
,

您是否将构建配置为使用支持库实现?

https://developer.android.com/guide/topics/graphics/vector-drawable-resources#vector-drawables-backward-solution

getListClass

否则,构建系统将为较低的SDK版本创建后备(非矢量)资源,而不使用支持实现。