moctavianro
moctavianro

Reputation: 71

Change button background on touch

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)

Upvotes: 5

Views: 12411

Answers (2)

RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

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

Upvotes: 19

Vinayak Bevinakatti
Vinayak Bevinakatti

Reputation: 40513

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>

Upvotes: 0

Related Questions