Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a selector to change an ImageButton image?

How do I make an ImageButton image change its image when you press it?

like image 360
Broo Avatar asked Dec 12 '22 22:12

Broo


1 Answers

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.

like image 158
Broo Avatar answered Jan 07 '23 21:01

Broo