Android使用矢量绘图功能在带有Android的customview中绘制图像<;5.

Android使用矢量绘图功能在带有Android的customview中绘制图像<;5.,android,android-vectordrawable,Android,Android Vectordrawable,我有一个CustomView类,有TextView和ImageView之类的 public class CustomView extends LinearLayout { private ImageView imgImage; ... public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defS

我有一个
CustomView
类,有
TextView
ImageView
之类的

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);
    }
}
style.xml中

<declare-styleable name="CustomViewStyle">
     <attr format="string" name="text"/>
     <attr format="reference" name="image"/>
</declare-styleable>
当我喜欢用它的时候

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

如何使矢量在android<5的自定义视图中工作?任何帮助或建议都将不胜感激。

您可以使用
VectorDrawableCompat.create(Resources,int,Theme)
获得
VectorDrawableCompat
实例(它是
Drawable
的子类)。将发布的代码作为模板,您可以编写如下内容:

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);
}
请注意,您可以将
Context
对象从构造函数传递到此方法中,然后对
create()
的第三个参数使用
Context.getTheme()
而不是
null

 Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_android_black.xml from drawable resource ID #0x7f060054
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);
}