Boron
Boron

Reputation: 129

How to apply vector drawable to an image programmatically?

I have a bunch of SVG images(5) that I've converted to vector drawables in Android Studio. I need to hardcode them in my adapter but I can't figure out how to apply.

Using a regular image(a .png or jpg) this is how I would put them in an array.

int[] images = {R.drawable.image_one.png,R.drawable.image_two.png};

and apply to the image like below:

imageView.setImageResource(images[position]);

how can I achieve the same with vector drawables(the extension file ends with .xml)

Upvotes: 0

Views: 1956

Answers (2)

ror
ror

Reputation: 3500

Both png drawables and vector drawables can be set like this:

  1. Say, on file system your drawable is hello.xml or hello.png
  2. You set it like imageView.setImageResource(R.drawable.hello) in both cases (you don't have to specify extensions)

I would recommend using @DrawableRes annotation next to your type definition, for better compiler checks (@DrawableRes int [] images = ...)

Upvotes: 0

Kalpesh Kulye
Kalpesh Kulye

Reputation: 149

Using getResources() method as follows

imageView.setImageResource(getResources().getDrawable(R.drawable.image_one));

Upvotes: 1

Related Questions