如何以编程方式将 VectorDrawable 设置为 ImageView 的图像

How to set VectorDrawable as an image for ImageView programmatically

我想在 Android Studio 中将一些 vectorDrawables 设置为 ImageView

我可以轻松地设置 png 和 jpg 可绘制对象,但是当我想设置 VectorDrawable 时,它​​在 imageview 上不起作用。

img.setImageResource(R.drawable.ic_home);

ic_home 是 VectorDrawable,此代码不起作用。

根据官方 android developer blog,vectorDrawables 的 setImageResource() 方法在运行时没有变化。

If you’re changing drawables at runtime, you’ll be able to use the same setImageResource() method as before - no changes there. Using AppCompat and app:srcCompat is the most foolproof method of integrating vector drawables into your app.

有关详细信息,请查看 Google 开发人员 AppCompat — Age of the vectors 这篇精彩的文章。

如果您担心向后兼容性,那么您应该使用 AppCompatImageView 而不是图像视图。通过下面的代码。

<android.support.v7.widget.AppCompatImageView
    android:id="@+id/iv_about"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
   app:srcCompat="@drawable/ic_vector_image"
    />

java

AppCompatImageView image = (AppCompatImageView) findViewById(R.id.iv_about);
image.setImageResource(R.drawable.ic_vector_image);

下面的代码需要加入build.gradle

android { defaultConfig{ vectorDrawables.useSupportLibrary = true } }

而且它将服务于app:srcCompat的视角。

如果您想使用矢量绘图(小于或大于 API 21),只需执行以下操作:

以编程方式设置图像(例如在您的 activity 中):

imageView.setImageResource(R.drawable.ic_left_arrow_blue); 

或 XML:

app:srcCompat="@drawable/your_vector_name"

在您应用的 build.gradle 中,您需要包括:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

对于小于 API 21 的矢量支持,将以下内容添加到 onCreate

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);  

我在回收站视图中有一个矢量,我正在使用 img.setImageResource(R.drawable.ic_home),它无法正常工作,就像在回收站视图的某些项目中形成的其他图像一样。然后我使用了 img.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_home)) 这有效。

使用这个:

android.support.v7.widget.AppCompatImageButton, 
android.support.v7.widget.AppCompatImageView,
android.support.v7.widget.AppCompatTextView 

而不是 ImageButtonImageView

如果使用矢量类型图像。主要用于自定义视图。

对于那些想要以编程方式加载矢量可绘制对象以用于其他用途(例如设置 drawableLeft 或其他用途)的用户,您可以使用:

Drawable drawable = AppCompatResources.getDrawable(context, drawableRes);

其中上下文是 AppCompatActivity。

for Java 代码使用:

formate_img.setImageResource(R.drawable.ic_text);//ic_text is a Vector Image

并且 XML 使用:

<android.support.v7.widget.AppCompatImageView
        android:id="@+id/search_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_weight="1"
        ads:srcCompat="@drawable/ic_barcode" //for Vector Image
        tools:ignore="VectorDrawableCompat" />

从您的 drawable 文件夹中删除两个文件夹,然后重建您的项目,它将正常工作