android button selector

pearmak picture pearmak · Dec 24, 2012 · Viewed 195k times · Source

This is a button selector such that when normal it appears red, when pressed it appears grey.

I would like to ask how could the code be further directly modified such that when PRESSED the text size and color could also change? Many thanks!

<item android:state_pressed="true" >         
    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
        <stroke android:width="2dp" android:color="@color/black" />
        <solid android:color="@color/grey"/>
        <padding android:left="5dp" android:top="2dp" 
            android:right="5dp" android:bottom="2dp" /> 
        <corners android:radius="5dp" /> 
    </shape>    
</item>

<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
        <stroke android:width="2dp" android:color="@color/black" />
        <solid android:color="#FF6699"/>
        <padding android:left="5dp" android:top="2dp" 
            android:right="5dp" android:bottom="2dp" /> 
        <corners android:radius="5dp" /> 
    </shape>
</item>

Answer

Chintan Rathod picture Chintan Rathod · Dec 24, 2012

You just need to set selector of button in your layout file.

<Button
     android:id="@+id/button1"
     android:background="@drawable/selector_xml_name"
     android:layout_width="200dp"
     android:layout_height="126dp"
     android:text="Hello" />

and done.

Edit

Following is button_effect.xml file in drawable directory

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/numpad_button_bg_selected" android:state_selected="true"></item>
    <item android:drawable="@drawable/numpad_button_bg_pressed" android:state_pressed="true"></item>
    <item android:drawable="@drawable/numpad_button_bg_normal"></item>

</selector>

In this, you can see that there are 3 drawables, you just need to place this button_effect style to your button, as i wrote above. You just need to replace selector_xml_name with button_effect.