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条回答
▲ chillily
2楼-- · 2020-02-17 06:53

I had a vector in recycler view I was using img.setImageResource(R.drawable.ic_home) which didn't worked properly like some other image get formed in some item of recycler view. Then I used img.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_home)) this worked .

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-17 06:58

if you are concerned with the backward compatibility then you should use AppCompatImageView instead of image view. go through the code below.

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

below code need to add in build.gradle

android { defaultConfig{ vectorDrawables.useSupportLibrary = true } }

And it will serve the perspective of app:srcCompat.

查看更多
登录 后发表回答