android change button icon when clicked

user1909680 picture user1909680 · Feb 24, 2013 · Viewed 32.8k times · Source

I want to know if there is a way of changing a button image when it is clicked. Initially the button has a pause icon. When it is clicked I want the play icon to be displayed. Each time the button is clicked the icon should vary between play and pause.

Is there any way of doing this?

XML Layout file:

<ImageButton
    android:id="@+id/play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="109dp"
    android:src="@drawable/play_btn"
    android:background="@null" />

play_btn.xml

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

Answer

Justin picture Justin · Feb 24, 2013

Android's Toggle Button with a custom selector sounds like what you want.

You might use something like this for your button's selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/play_icon" android:state_checked="true" />
    <item android:drawable="@drawable/pause_icon" android:state_checked="false" />
</selector>