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

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

问题描述

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

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

我可以设置png和jpg很容易绘制,但是当我想设置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.

推荐答案

如果你想使用矢量drawables(比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天全站免登陆