最近在运行API 16的设备上收到了崩溃报告,内容为:
org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
据我所知,它是由API 16中对VectorDrawable的缺少支持引起的。
老实说,我不知道我有这样的可绘制对象,根据
git log
,当我启用矢量库时,它们似乎是自动生成的。我想定义一个复选框背景,是否应该离开VectorDrawable?如果是这样,我应该如何支持较低的API?
如果我删除它们,会不会再次自动生成它们?
这是复选框声明:
<CheckBox
android:id="@+id/reminder_enabled_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:padding="10dp"
android:button="@drawable/notification_icon_checkbox" />
这是选择器:(
notification_icon_checkbox
):<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/ic_notifications_none_black_24dp" />
<item android:state_checked="true" android:drawable="@drawable/ic_notifications_black_24dp" />
<item android:drawable="@drawable/ic_notifications_none_black_24dp" /> <!-- default state -->
</selector>
可绘制的
ic_notifications_none_black_24dp
既是.png
文件,又是VectorDrawable
xml文件:<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M11.5,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.9,2 2,2zm6.5,-6v-5.5c0,-3.07 -2.13,-5.64 -5,-6.32V3.5c0,-0.83 -0.67,-1.5 -1.5,-1.5S10,2.67 10,3.5v0.68c-2.87,0.68 -5,3.25 -5,6.32V16l-2,2v1h17v-1l-2,-2z" />
</vector>
最佳答案
将此添加到您的模块级build.gradle
vectorDrawables.useSupportLibrary = true
将此添加到您的活动/片段中
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
从XML移除Vector drawable
<CheckBox
android:id="@+id/reminder_enabled_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:padding="10dp"
/>
像这样以编程方式设置CheckBox自定义可绘制对象
CheckBox cb = findViewById(R.id.reminder_enabled_checkbox);
cb.setButtonDrawable(AppCompatResources.getDrawable(getContext(), R.drawable.notification_icon_checkbox));
关于android - 使用VectorDrawable作为CheckBox背景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43501930/