How do I make an ImageButton image change its image when you press it?
I hope you find this helpful.
This can all be done in the XML.
1) Import your images for both pressed and unpressed states into the res/drawable-whichever folder
2) Make your selectors. Right click on a drawable folder and select New/Android xml file. Put in the name eg "ok_button_selector.xml" and choose "selector" as the root element from the menu below. You will need to create a different selector for each button on the screen.
3) In each selector file you need to define the image that will display when clicked, like this:
<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:state_pressed = "true"
android:drawable="@drawable/search_icon_pressed"/>
<item
android:drawable="@drawable/search_icon"/>
</selector>
They have to be in this order as the last is the default.
4) In your layout file use the android:onClick="myButtonClicked" method to define the buttons clicked behaviour. This saves having to use click listeners. Just make sure your java method has the same name :-)
5) Within the ImageButton tags define the attribute android:src="@drawable/ok_button_selector" instead of the usual image file.
Thats it! You don't need any extra code in your java onClick method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With