How can I create a button that changes its background image to represent the default, pressed or focused states?
Asked
Active
Viewed 84 times
0
-
See [android button selector](http://stackoverflow.com/questions/14023886/android-button-selector). Please do google it before asking same questions again. Thanks. – Shobhit Puri Nov 30 '14 at 00:11
2 Answers
0
Quite easy to do using a selector.
Create a new xml file inside the drawable folder containing the following:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_selected" android:state_selected="true"></item>
<item android:drawable="@drawable/drawable_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/drawable_default"></item>
</selector>
Then refer to this selector in your Button:
<Button
android:id="@+id/button"
android:background="@drawable/selector_you_just_made"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button" />
More documentation and other possible states can be found here.

James
- 1,036
- 1
- 8
- 24
0
XML drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused"
android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>
Button:
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
android:background="@drawable/button_custom" />
Here in section Custom background is more info

Petr Duchek
- 1,223
- 14
- 19