使用VectorDrawable作为CheckBox的背景

3

最近收到一份在运行API 16的设备上的崩溃报告,报告内容如下:

org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector

据我所见,这是由于 API 16 中对 VectorDrawable 的支持不完整而产生的。
说实话,我不知道我有这样的可绘制对象,根据 git 日志,看起来它们是在启用矢量库时自动生成的。
我想定义一个复选框背景,我应该保留 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>

你能展示一下你的向量 XML 吗? - Luiz Fernando Salvaterra
@LuizFernandoSalvaterra 已添加。 - SagiLow
你是否正在使用矢量图兼容性? - Muhammad Babar
请查看以下链接:https://codelabs.developers.google.com/codelabs/material-design-style/index.html?index=..%2F..%2Fio2016#5 - Muhammad Babar
@MuhammadBabar 这是 VectorDrawable(我使用的),而不是 vector drawable compat(我可能误解了)。 - SagiLow
显示剩余2条评论
1个回答

4

将以下内容添加到您的模块级 build.gradle 中:

vectorDrawables.useSupportLibrary = true

将以下内容添加到您的Activity/Fragment中

 static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

从XML中删除矢量可绘制图形

<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的自定义Drawable

CheckBox cb = findViewById(R.id.reminder_enabled_checkbox);

cb.setButtonDrawable(AppCompatResources.getDrawable(getContext(), R.drawable.notification_icon_checkbox));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接