Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button on click visual state change

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.

like image 387
marchemike Avatar asked May 03 '12 05:05

marchemike


3 Answers

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>
like image 174
Krishnakant Dalal Avatar answered Oct 16 '22 17:10

Krishnakant Dalal


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>
like image 26
K_Anas Avatar answered Oct 16 '22 17:10

K_Anas


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*/
}
like image 1
drulabs Avatar answered Oct 16 '22 17:10

drulabs