i want to change the green background of a button when this is touched without using OnTouchListener. i have this situation: i put some butons in a layer, then the layer in another layer, and the last layer in onother layer. when i touch the button the background is changing(i m using OnTouchListener right now) but if i drag the finger outside of the button and then get it out of the screen the background of the button remains the image from the state when it s touch(otherwise if i click the button and the the finnger off the button it is k the background is changing)
Asked
Active
Viewed 1.2k times
5
-
if u r not using xml show ur code , i will make it clear.. – RajaReddy PolamReddy Nov 15 '11 at 07:56
2 Answers
19
1. Prepare 3 images for button states, and put it into resource/drawable
folder.
2. create a new XML file in res/drawable/
folder, in whatever name you want, in this case, we just give a name as my_button.xml
. This file defined which button state is belong to which image.
Now, you can refer to this button via this Id : @drawable/my_button.
File : res/drawable/my_button.xml
create xml file using the button image like this with my_button.xml
in drawable
folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused_orange"
android:state_focused="true" />
<item android:drawable="@drawable/button_normal_green" />
</selector>
add a normal button, and attach the background image to above “my_button” via
android:background:@drawable/my_button

RajaReddy PolamReddy
- 22,428
- 19
- 115
- 166
-
thanks. can u please provide me the code example(i m not using xml in creating my gui) – moctavianro Nov 15 '11 at 07:40
-
@user1021692: he meant,you should use this xml file in your button tag.please see the edit of this answer – Hiral Vadodaria Nov 15 '11 at 07:52
-
i ve seen the xml is k what is there but i want a code example not an xml example – moctavianro Nov 15 '11 at 09:34
-
is this solved your problem , if yes please accept the answer. – RajaReddy PolamReddy Nov 24 '11 at 10:54
0
The selector will be as below
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_pressed" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/btn_focused" /> <!-- focused -->
<item android:drawable="@drawable/btn_default" /> <!-- default -->
</selector>

Vinayak Bevinakatti
- 40,205
- 25
- 108
- 139