AnimatedVectorDrawable 支持 < 24

AnimatedVectorDrawable support < 24

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

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,则此 运行 完美,否则会崩溃。我需要支持 android 最低 SDK 21 的设备。

我的问题是

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

但是,如果您想要更通用的方法,则必须使用 AppCompatResources.getDrawable() 而不是 ResourcesCompat.getDrawable(),因为它正确地考虑了 VectorDrawableCompatAnimatedVectorDrawableCompat、并且 AnimatedStateListDrawableCompat 类 以与所有 API 级别兼容的方式:

val drawable = AppCompatResources.getDrawable(
    this, // your Context
    R.drawable.animation)

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

    if (drawable is Animatable) {
        drawable.start()
    }
}

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

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

android {
  defaultConfig {
    vectorDrawables.useSupportLibrary = true
  }
}

否则,构建系统将为较低版本的 SDK 创建回退 (non-vector) 资源,而不是使用支持实现。