ImageButton touch feedback

739 Views Asked by At

how can I implement a touch feedback for ImageButtons? I want the image button to change the image when the button is touched. I already searched, but after trying some things that didn't worked I'm a bit desperate. Is a selector the right thing for this problem and how does this work?

My current try is to create a new .xml file in the drawable folder. There I would put a selector, this is my current code for the .xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<item
    android:state_pressed="true"
    android:drawable="@drawable/testbuttonimageselected" />
<item
    android:drawable="@drawable/testbuttonimage" />
</selector>

And this is my current code for the .java file:

btnTest = (ImageButton) findViewById(R.id.btnTest);
btnTest.setOnClickListener(new View.OnClickListener() {

    public void onClick(View button) {
       //Set the button's appearance
       button.setSelected(!button.isSelected());

        if (button.isSelected()) {
           //Handle selected state change
        } else {
           //Handle de-select state change
        }
    }
});
1

There are 1 best solutions below

2
On

You can easily do this by using a state list, and assigning a different image to each state: https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList