I made my own background for a button and I want the button to change when it is clicked. I found this code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/boutonnpousse" android:state_pressed="true"/>
<item android:drawable="@drawable/boutonn"/>
</selector>
But where do I use it? I tried just pasting it in main XML file but it isn't working.
You will save this as an xml file in res/drawable
folder. If this folder does not exist, create it. In the example, the file name that I use is selector_drawable_name.xml
Following this, whenever you use a Button, and want it to have the click effect, set its background to this drawable:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:background="@drawable/selector_drawable_name" />
Result: When the button's state changes to state_pressed
, the background selected will be @drawable/boutonnpousse
. Default (in every other state) will be @drawable/boutonn
.
By the way...you can use the state list XML generator in the following site:
http://myandroidsolutions.blogspot.co.il/p/android-state-list-generator-v2.html
Just check the states you would like to add and assign drawable file names in the corresponding fields at the bottom. The generator will generate the XML elements in the right order using the right states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With