Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply Different Style to Button When Pressed

Is there a way to apply a style to a button when the button is pressed?

If I have a style in style.xml:

<resources>
    <style name="test">
        <item name="android:textStyle">bold</item>
    </style>
</resources>

a selector in button.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/test_pressed"
              style="@style/test"
          android:state_pressed="true"/>
    <item android:drawable="@drawable/test_focused"
          android:state_focused="true"/>
    <item android:drawable="@drawable/test_normal"/>
</selector>

then how would I reference button.xml in my layout?

<Button
        ...
        android:???="button"/>

Thanks!

like image 205
user440308 Avatar asked Sep 16 '10 19:09

user440308


2 Answers

Romain Guy suggests it is not possible:

http://code.google.com/p/android/issues/detail?id=8941

"Selector works only for drawables, not text appearances. There is currently not plan to make this happen."

like image 179
esilver Avatar answered Oct 27 '22 17:10

esilver


You can achieve this by using an XML button definition.

Create an XML file in your drawable folder as follows:

<?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/green_button" /> 

        <!-- <item android:state_focused="true"
        android:drawable="@drawable/button_focused" /> --> 

        <item android:drawable="@drawable/black_button" />
</selector>

As you can see this allows you to define different button images to use for the different states (black_button, green_button etc should be .PNG files in your drawable folder also)

Now, from your layout.xml file you can just set the button background to point to the button selector:

<Button android:text="Play" android:id="@+id/playBtn"
            android:background="@drawable/button_selector"
            android:textColor="#ffffff" />

The Selector XML can then be referenced from teh drawable folder like any image file can.

like image 43
rhinds Avatar answered Oct 27 '22 17:10

rhinds