Search code examples
androidandroid-vectordrawable

Android using vector drawable for image in customview with android < 5


I have a CustomView class with a TextView and a ImageView like

public class CustomView extends LinearLayout {
    private ImageView imgImage;
    ...

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }
    private void init(AttributeSet attrs) {
        LayoutInflater.from(getContext()).inflate(R.layout.custom_layout, this, true);
        imgImage = (ImageView) findViewById(R.id.image);

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CustomViewStyle);
        Drawable drawable = ta.getDrawable(R.styleable.CustomViewStyle_image); // CRASH LINE

        ta.recycle();
        imgImage.setBackground(drawable);
    }
}

in style.xml

<declare-styleable name="CustomViewStyle">
     <attr format="string" name="text"/>
     <attr format="reference" name="image"/>
</declare-styleable>

build.gradle

android {
  defaultConfig {
    ...
    vectorDrawables.useSupportLibrary = true
  }
}

When I using it like

<.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:image="@drawable/ic_android_black" //ic_android_black is a vector drawable
        />

it will throw a Exception in android 4.4, it work well from android 5

 Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_android_black.xml from drawable resource ID #0x7f060054

How to make vector work in custom view with android < 5? Any help or suggestion would be great appreciated.


Solution

  • You can use VectorDrawableCompat.create(Resources, int, Theme) to obtain a VectorDrawableCompat instance (which is a subclass of Drawable). Taking the code you posted as a template, you could write something like this:

    TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CustomViewStyle);
    int drawableId = ta.getResourceId(R.styleable.CustomViewStyle_image, 0);
    ta.recycle();
    if(drawableId != 0){
        Drawable drawable = VectorDrawableCompat.create(getResources(), drawableId, null);
    }
    

    Note that you could pass the Context object from your constructor into this method and then use context.getTheme() instead of null for the third argument to create().