How to set VectorDrawable as an image for ImageVie

2020-02-17 06:32发布

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

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 is VectorDrawable and this code doesn't work.

8条回答
The star\"
2楼-- · 2020-02-17 06:36

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); 

or by XML:

app:srcCompat="@drawable/your_vector_name"

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

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

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

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);  
查看更多
在下西门庆
3楼-- · 2020-02-17 06:36

As per official android developer blog, no changes for setImageResource() method at runtime for vectorDrawables.

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.

For more details, check out this nice article AppCompat — Age of the vectors by Google Developer.

查看更多
4楼-- · 2020-02-17 06:37

Delete two folders form your drawable folder then rebuild your project it will work properlyenter image description here

查看更多
何必那么认真
5楼-- · 2020-02-17 06:42

for Java Code use:

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

and for XML use:

<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" />
查看更多
我只想做你的唯一
6楼-- · 2020-02-17 06:45

Use this:

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

instead of ImageButton, ImageView etc.

If vector type image is used. Mainly for custom views.

查看更多
Luminary・发光体
7楼-- · 2020-02-17 06:52

For those who want to load a vector drawable programmatically for other uses, such as setting a drawableLeft or otherwise, you can use:

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

where the context is a AppCompatActivity.

查看更多
登录 后发表回答