SagiLow
SagiLow

Reputation: 6029

Using VectorDrawable as CheckBox background

Recently got a crash report on a device running API 16 saying :

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

As far as I've seen, it's originated by a missing support in API 16 for VectorDrawable.
Honestly I had no idea I have such drawables and according to the git log it looks like they were auto-generated as I enabled the vector library.
I want to define a checkbox background, should I leave the VectorDrawable ? If so, how should I support lower API's ? If I remove them, wouldn't they be auto-generated again?

Here is the checkbox declaration:

<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" />

Here is the selector : (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>

The drawable ic_notifications_none_black_24dp is both .png file and VectorDrawable xml file :

<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>

Upvotes: 3

Views: 965

Answers (1)

Mansukh Ahir
Mansukh Ahir

Reputation: 3543

Add this in your module-level build.gradle

vectorDrawables.useSupportLibrary = true

Add this in your Activity/Fragment

 static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

Remove Vector drawable from 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"
/>

Set CheckBox custom drawable programmaticully like this

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

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

Upvotes: 4

Related Questions