问题描述
我的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设备。
我的问题是
解决方法
如果您知道自己正在使用动画矢量,则可以使用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
,
您是否将构建配置为使用支持库实现?
getListClass
否则,构建系统将为较低的SDK版本创建后备(非矢量)资源,而不使用支持实现。