Android 在 android < 5 的自定义 View 中使用矢量可绘制图像

标签 android android-vectordrawable

我有一个带有 TextViewImageViewCustomView

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>

构建.gradle

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

当我使用它的时候

<.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 4.4 中抛出一个Exception,它在 android 5 中运行良好

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

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

最佳答案

您可以使用 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 对象传递给此方法,然后使用 context.getTheme() 而不是 null create() 的第三个参数。

关于Android 在 android < 5 的自定义 View 中使用矢量可绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047233/

相关文章:

Android 如何在 ListView 中仅显示同一数组中的某些项目?

java - android.content.res.Resources$NotFoundException : Resource ID #0x0 java exception

android - 我可以像使用 9 补丁一样使用矢量可绘制对象吗?

android - VectorDrawable 未显示或绘制错误

android - 如何通过指定的x和y坐标获取VectorDrawableCompat的像素颜色

Android 如何删除矢量资源 Drawable 的内部填充

android - 如何使用 Android 支持库 23.2 将 vectorDrawable 用作推送通知的图标? setSmallIcon 给出错误

android - FragmentPagerAdapter getItem 位置错误

android - 检查用户是否购买了应用

android - SimpleXML Parser android获取HTML TAG