Button on click visual state change

26,967

Solution 1

Use this XML: save it in drawable folder and set as the background drawable.

<?xml version="1.0" encoding="utf-8" ?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/category_listing_bg_img" /> 
<item android:state_pressed="true" android:drawable="@drawable/category_listing_bg_img_pressed" /> 
</selector>

Solution 2

add an xml file on your res/drawable folder name it button_selector.xml put also two drawable one for the pressed state and onother for unpressed or normal state. Finally add this two your xml file button selector and everything should work!! don't forget to set the @drawable/bytton_selector.xml as the background of your button on your main.xml file.

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">

     <item android:drawable="@drawable/btn_pressed" android:state_pressed="true"/>
       <item android:drawable="@drawable/btn_unpressed"/>

  </selector>

Solution 3

Yes there is. Implement onTouchListener. use the MotionEvent variable (lets say event) in onTouch method write this:

if (event.getAction() == MotionEvent.ACTION_DOWN){
    /*Code*/
}
if (event.getAction() == MotionEvent.ACTION_UP){
    /*Code*/
}

Solution 4

what you should do is create a selector (what Krishnakant Dalal was talking about). it handels how the UI element looks like at every single state it can be (presses, disabled, normal etc.)

for more about selectors read here: http://android-journey.blogspot.com/2009/12/android-selectors.html

Share:
26,967
marchemike
Author by

marchemike

programmer

Updated on February 24, 2020

Comments

  • marchemike
    marchemike about 4 years

    Is there any way to animate a button in Android so that when you click it it changes the background of the button to a pressed image?

    I'm only using the background property to show the image on the form button.