Android ImageButton state does not change

I have a problem with changing the state of ImageButton. When I click or rather touch the button, it remains as the same image. Here is the XML that I use as a selector.

<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/pushed" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/pushed" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pushed" /> <item android:drawable="@drawable/default" /> </selector> 

I call this selector from my main.xml as

 android:background="@drawable/imagechoice" 

imagechoice.xml is a file with a selector

I do not understand why this does not work, unless I have Java code, but everything I saw says that this should work.

+4
source share
5 answers

When using ImageButton, is this not the 'src' property that you should use, not the background?

+2
source

Make sure you copy the same images and XML button to each drawable folder (hdpi, ldpi, mdpi). This is how I solved this problem in my application.

Good luck :)

+2
source

I have almost the same XML and it works fine. Are you sure you are not replacing the reference code somewhere?

In another note, your XML can be simplified by using the cascading nature of state matching.

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/pushed" /> <item android:state_focused="true" android:drawable="@drawable/pushed" /> <item android:drawable="@drawable/default" /> </selector> 
+1
source

This is my xml button with my own custom image on it, and it works fine:

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/btn_off" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/btn_pressed" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/btn_pressed" /> <item android:drawable="@drawable/btn_off" /> </selector> 
0
source

Make sure you set the button background as shown below. I think that you are not setting the selector as the background, but not setting the image as the background.

  <Button android:id="@+id/b1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/button_up_selector" android:text="1" android:textColor="#fffafa" android:layout_marginRight="5dp" android:layout_marginBottom="5dp"/> 
0
source

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


All Articles