VectorDrawableCompat Resources$NotFoundException on KitKat and below

早过忘川 提交于 2019-11-27 09:13:45
Rakshith Kumar

To support versions before Lollipop, use

com.android.support:appcompat-v7:24.0.0 (or later)

support library.

And then, instead of

ContextCompat.getDrawable(view.getContext(), id);

use this one

AppCompatResources.getDrawable(view.getContext(), id);

I found the problem: I had my vector-drawables in drawable-anydpi/ - this produces this crash - when i move the drawables to drawable/ it works fine

I was able to use the vector drawables on pre-Lollipop devices by wrapping them in a StateListDrawable (a selector).

More precisely, I created a selector drawable in XML, and then added a single vector drawable in them :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/vector_ic_action_add" />
</selector>

I then use this "wrapped" drawable in my menu. If you want more information about how it works, check out this very useful post by Chris Banes.

as far as I've read on the docs there's only XML access for ImageView.

For the Menu you'll have to use in java.

toolbar.inflateMenu(menuResId);
toolbar.getMenu()
       .findItem(menuItemId)
       .setIcon(VectorDrawableCompat
                       .createFromResource(resource, drawableId);

To fix this issue, I had to add the following code at the application startup (Application subclass) :

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

In addition to :

  • Use app:srcCompat in layout definition (ImageButton view in my case) instead of android:src.
  • Activate in gradle : vectorDrawables.useSupportLibrary = true

If you are using vectorDrawableComapt and setting it in XML remember to do it the correct way:

app:srcCompat="@drawable/ic_add"

Source: https://android-developers.blogspot.co.uk/2016/02/android-support-library-232.html

I faced same issue but after some hour of wasting solved the issue

  1. Remove drawables make sure just have drawable
  2. In build.gradle use

    defaultConfig {vectorDrawables.useSupportLibrary = true}

    1. Make set vector drawable to ImageView as below
      <ImageView android:id="@+id/ivLogo" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/your_selector" app:srcCompat="@drawable/ic_your_vector_logo" />

    2. Your activity must extends AppCompatActiviity instead of Activity

I hope your problem solved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!