how to change the ImageButton's image when it is pressed and released?

David picture David · Jun 30, 2011 · Viewed 10.8k times · Source

I want that in my android application, the ImageButton change its image when it is pressed and released, and when it is pressed released again, the image for ImageButton will be changed back , how to do that?

Answer

Sunil Kumar Sahoo picture Sunil Kumar Sahoo · Jun 30, 2011

create a selector (it is an xml file) put in drawable folder. and in xml five path of that xml instaed of actual image android:background="@drawable/imageselector" or in program also you can get the same using imageview.setBackgroundDrawable(R.drawable.imageselector)

Following is my selector imageselector.xml

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