0

I'm using a VectorDrawable defined in an xml, on an ImageView used as a button. I want the colour of the image to change when the user click on it.

Here is my current vector xml:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:width="24dp"
    android:height="24dp">
    <path
        android:pathData="<vector data>"
        android:fillColor="<vector's colour>" />
</vector>

I can use a selector with two implementations of my vector, one with the colour A and the other one with the colour B:

EDITED

vector_image_a.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    ...>
    <path
        ...
        android:fillColor="@color/colour_A" />
</vector>

vector_image_b.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    ...>
    <path
        ...
        android:fillColor="@color/colour_B" />
</vector>

selector.xml

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/vector_image_a" android:state_pressed="true" />
    <item android:drawable="@drawable_vector_image_b" />
</selector>

But I have more than one clickable image in my app and each time I want only the colour of the image to change when the user presses on it. If I carry on with the implementation above, for each clickable image I will end with 3 files:

  • one for the image with the colour A
  • one for the image with the colour B
  • one for the selector

So I was wondering if it is possible to use a selector directly on the vector image colour (android:fillColor attribute). Example:

vector_image.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    ...>
    <path
        ...
        android:fillColor="drawable/selector_colour" />
</vector>

selector_colour.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colour_A" android:state_pressed="true" />
    <item android:color="@color/colour_B" />
</selector>

I tried but apparently it doesn't work?

Eselfar
  • 3,759
  • 3
  • 23
  • 43
  • `I was wondering if it is possible to use a selector` Did you try the opposite way: a selector which points to different VectorDrawables, instead? – Phantômaxx Jan 13 '17 at 18:22
  • Thx for replying. I've updated the question as it was not really clear apparently. If I understand correctly what you suggest is my current implementation. The problem is, I have more than one image. So if I keep it like that I will end with a lot a files. – Eselfar Jan 16 '17 at 09:26

1 Answers1

0

I have found the answer to my question in that post. All I have to do is use the vector image as the source of my ImageView and then use the selector (selector_colour.xml) as a tint.

Community
  • 1
  • 1
Eselfar
  • 3,759
  • 3
  • 23
  • 43