androidandroid-imagebuttontint

Change Tint Image Button after pressed


I am trying to create an ImageButton able to change the icon color after pressing. I want to do that in my XML file. I have the following code:

...

<ImageButton
        android:id="@+id/stop_button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:src="@drawable/stop_icon"
        android:background="@drawable/stop_button"
        android:tint="@color/ship_cove"
        app:layout_constraintBottom_toTopOf="@id/bottom_icon_guideline"
        app:layout_constraintLeft_toRightOf="@id/start_icon_guideline"
        app:layout_constraintRight_toLeftOf="@id/end_icon_guideline"
        app:layout_constraintTop_toBottomOf="@id/mediatop_icon_guideline" />

And here is my @drawable/stop_button.xml file content:

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/cornflower_blue">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/oxford_blue" />
            <corners android:radius="8dp" />
        </shape>
    </item>
</ripple>

As I stated before, my purpose is to change my stop_icon tint after pressing my stop_button, but I do not know how I can do that. Can anyone help me?

Note: if my button is not pressed, I want my stop_icon with the color @color/ship_cove. If it is, I want the color @color/mirage.


Solution

  • Instead of color create a color selector with a pressed state.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:color="pressed_color" android:state_pressed="true" />
        <item android:color="default_color" />
    </selector>
    

    And use this selector for the color of the icon. The rest should be taken by the system.