我遇到了与 VectorDrawables 的新向后兼容性问题。 在支持库 23.2 中,引入了向后兼容 Android VectorDrawables 的新功能。
我有一个分配给 SelectorDrawable 的 ImageView。这个 Drawable 包含几个 VectorDrawables,所以我想我应该使用 app:srcCompat 来实现兼容性。但它不适用于我的带有 android 4.1.2 的 Galaxy S2。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_gps_fixed_24dp"android:state_activated="true" android:state_selected="true"></item>
<item android:drawable="@drawable/ic_gps_not_fixed_24dp" android:state_activated="true" android:state_selected="false"></item>
<item android:drawable="@drawable/ic_gps_not_fixed_24dp" android:state_activated="false" android:state_selected="true"></item>
<item android:drawable="@drawable/ic_gps_off_24dp" android:state_activated="false" android:state_selected="false"></item>
<item android:drawable="@drawable/ic_gps_not_fixed_24dp"></item>
</selector>
所有可绘制对象都是矢量 xml 文件。
当将此 SelectorDrawable 与 srcCompat 一起使用时,我收到此错误:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_gps_fixed_24dp.xml from drawable resource ID #0x7f0201c1
at android.content.res.Resources.loadDrawable(Resources.java:1951)
at android.content.res.Resources.getDrawable(Resources.java:672)
at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:173)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881).xml from drawable resource ID #0x7f0201c1
使用 android:src 更糟糕。
如果我将其中一个矢量可绘制对象与 app:srcCompat 一起使用,则一切正常。所以我猜这是 SelectorDrawable 和兼容性的问题。
有没有人遇到过同样的问题并找到了解决方案,或者目前无法在 Android 5 之前的 SelectorDrawables 中使用 VectorDrawables?
速览:
- 编译目标 API 23
- 支持 Libraray 23.3.0
- vectorDrawables.useSupportLibrary = true
- Gradle 2.0
最佳答案
自从我提出这个问题以来,有些事情发生了变化,所以我会自己回答。
支持库 23.4.0 重新启用了对来自 Ressources 的 VectorDrawables 的支持:Android Support Library 23.4.0 available now
您可以在 Google I/O 2016 的此 Actor 阵容中找到更多信息: What's new in the support library - Google I/O 2016
您需要将此添加到您希望在低于 Android 5.0(代号 Lollipop,API 级别 21)的设备上使用 VectorDrawables 的每个 Activity:
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
因此,您现在可以在 DrawableContainers 中使用 VectorDrawables,但它仍然会导致上述来源中提到的一些问题,因此请谨慎使用。
到目前为止,我还没有在我的应用程序中重新启用此功能,但我将在下一个主要版本中将我的很多图标更改为 VectorDrawables,然后将深入探讨这个主题。
关于带有 VectorDrawables srcCompat 的 Android Selector Drawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36741036/