Android: How to switch ImageButton image when user release button?

I try to make it so that as long as the user touches the button, it shows one image, and when the user releases the button, it returns to the default image.

I am 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 tried several things with the selector, but it always produces the same behavior: the button starts with the default image, then I click on it and it changes to the β€œrecord_on” image and it never returns to the default image when I'm letting go

Is there a way to get this behavior using ImageButton, or should I use something else?

+4
source share
2 answers

It turns out I prematurely consumed the touch event in my onTouch () implementation. When I saw the ACTION_UP event, I consumed it by returning true, and therefore the event propagation was stopped before the selector received it. By returning false instead, the selector behavior is triggered and the image returns to default.

In other words, I'm n00b.

The reason I hadn't noticed this before was because the ACTION_DOWN event seemed to work fine, and I consumed it too. Later, I discovered that this was an ACTION_MOVE event, not an ACTION_DOWN event, which caused a button image to change, as I returned false for all other events.

0
source

Perhaps you should take a look at the standard XML resource for Button / ImageButton , which looks like $ANDROID_HOME/platforms/$PLATFORM/data/res/drawable/btn_default.xml (where $ANDROID_HOME is where you have the SDK installed, and $PLATFORM - any version of the API you are interested in).

Their "normal" state:

 <item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" /> 
0
source

Source: https://habr.com/ru/post/1300530/


All Articles