Android Using layer-list for button selector
Step-1create three different layer_list xml under drawable folder for three different state of button. example the name of those xml is layer1.xml, layer2.xml, layer3.xml
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="270" android:startColor="#0000ff" android:endColor="#0000dd" android:type="linear" /> </shape> </item></layer-list>
Step-2create a selector xml named as btn_background.xml and pass the layer_list xml in drawable attribute
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/layer1"> </item> <item android:state_focused="true" android:drawable="@drawable/layer2"> </item> <item android:drawable="@drawable/layer3"> </item></selector>
step-3Set the selector xml as background of the button android:background="@drawable/btn_background"
Mygod's answer is actually better than the accepted one. It works and only needs one xml file. Here's something similar that I did. It sets the background under a drawable with transparencies. The same could be done with a background and a shape:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true"> <layer-list> <item android:drawable="@color/Black"/> <item android:drawable="@drawable/notes_white"/> </layer-list> </item> <item> <layer-list> <item android:drawable="@color/White"/> <item android:drawable="@drawable/notes_black"/> </layer-list> </item></selector>
Just replace the shape
tag with your layer-list
and everything will work fine.