Search code examples
androidshadowandroid-buttonstatespressed

Automatically alter button background and text appearance when pressed (like iOS)?


In iOS, if I set a button's background to an image, when I press the button, the whole content of the button (including the text) will be shadowed. Can I achieve the same effect in Android, or do I have to use different images for different states? Also, even if I use different images for different states, how do I make the text also shadowed? A dirty way is to set a OnClickListener to the button and programatically shadow the text when pressed, but are there any other ways?


Solution

  • I´ve been trying to find a solution for this for a while now but couldn´t find anything so I came up with a pretty neat solution which works on all image buttons. Just like iOS.

    • Create a Black, 10% transparent image and save it as PNG. I call it button_pressed.png. You can use this image, http://img84.imageshack.us/img84/7924/buttonpressed.png

    • Create a drawable called something relevant, I call it "button_pressed_layout.xml"

      <?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/button_pressed"  />
      </selector>
      
    • Now put your button image in the LinearLayout and then the Button inside the LinearLayout. In the Button use button_pressed_layout.xml as background.

          <LinearLayout 
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:background="@drawable/button_image">
              <Button
                  android:id="@+id/myButtonId"
                  android:text="@string/Continue"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:background="@drawable/button_pressed_layout"
                  android:textColor="#FFF"
                  android:textSize="16dp" >                   
              </Button>
          </LinearLayout>
      

    That´s it!