Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set clicked state for my custom button?

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.

like image 461
Guy Avatar asked Oct 03 '22 02:10

Guy


2 Answers

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.

like image 196
Vikram Avatar answered Oct 07 '22 18:10

Vikram


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.

like image 31
micnoy Avatar answered Oct 07 '22 17:10

micnoy