如何以编程方式将 VectorDrawable 设置为 ImageView 的图像 [英] How to set VectorDrawable as an image for ImageView programmatically

查看:18
本文介绍了如何以编程方式将 VectorDrawable 设置为 ImageView 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set some vectorDrawables to a ImageView in Android Studio.

我可以轻松设置 png 和 jpg drawable,但是当我想设置 VectorDrawable 时,它​​不适用于 imageview.

I can set png and jpg drawable easily but when i want to set VectorDrawable, it does not work on imageview.

img.setImageResource(R.drawable.ic_home);

ic_home 是 VectorDrawable 且此代码不起作用.

ic_home is VectorDrawable and this code doesn't work.

推荐答案

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

If you want to use vector drawables (less OR greater than API 21) just do the following:

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

Set the image programmatically (e.g. in your activity):

imageView.setImageResource(R.drawable.ic_left_arrow_blue); 

或通过 XML:

app:srcCompat="@drawable/your_vector_name"

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

In your app's build.gradle you need to include:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

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

And for vector support for less then API 21, add the following to onCreate:

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);  

这篇关于如何以编程方式将 VectorDrawable 设置为 ImageView 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆