Question

I'm trying to make it so that as long as a user is touching the button, it shows one image, and when the user releases the button, it goes back to a default image.

I'm trying to use a selector to make this happen:

<?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/record_on" />
  <item android:state_focused="true"
    android:drawable="@drawable/record_off" />
  <item android:drawable="@drawable/record_off" />
</selector>

I've tried a few things with the selector, but it always produces the same behavior: the button starts out with the default image, then I press it and it changes to the "record_on" image and it never goes back to the default image when I let go.

Is there a way to get this kind of behavior with an ImageButton, or should I be using something different?

Was it helpful?

Solution 2

It turns out that I was prematurely consuming the touch event in my onTouch() implementation. When I saw an ACTION_UP event, I was consuming it by returning true, and therefore the propagation of the event was stopped before the selector got it. By returning false instead, the selector behavior kicks in and the image returns to the default.

In other words, I'm a n00b.

The reason why I didn't notice this at first was because the ACTION_DOWN event seemed to be working fine, and I was consuming that one as well. I discovered later that it was the ACTION_MOVE event, not the ACTION_DOWN event, that was causing the button's image to change, since I was returning false for all other events.

OTHER TIPS

You might want to look at the standard XML resource for a Button/ImageButton, which appears to be $ANDROID_HOME/platforms/$PLATFORM/data/res/drawable/btn_default.xml (where $ANDROID_HOME is where you have your SDK installed and $PLATFORM is whatever API version you're interested in).

Their "normal" state is:

<item android:state_enabled="true"
    android:drawable="@drawable/btn_default_normal" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top