Alex Rivera | Logout

Android Set ImageButton as Toggle

Asked 2010-04-26T20:38:14.587
18

How can I have an imagebutton stay in the 'pressed' state when it is clicked? Basically I just want the background to be the depressed background, but I can't figure out how to set it. At the moment, I've just copied the selected button background into my res folder, but when I set it as the background, it becomes blurry (since the original image is bigger than the button itself).

Normal Background: alt text http://img707.imageshack.us/img707/9199/ss20100426163452.png What I'm getting: alt text http://img707.imageshack.us/img707/912/ss20100426163357.png alt text http://img3.imageshack.us/img3/8304/ss20100426163623.png

Also I don't believe I can actually use this method considering the many different UI layouts. The button should stay pressed as per the UI the user is using.

Edit
Report

1 Answer

41

There are a few ways of doing this:

First, you can simply use an ImageButton, and manually toggle its image drawable on click in Java. This is what the stock Music player on Android does for the shuffle button, for example. Although you won't have control over the button background in its checked state, you'll be able to swap out the image, which may be favorable from an Android UI-consistency perspective.

Another option is to use a complex set of drawables and nine-patches to get an image inside a ToggleButton, with the option of changing the background and/or the image resource upon toggle. That's the option I'll show below. But remember, be cautious about UI consistency before doing this.


res/layout/foo.xml

...
<ToggleButton
    android:textOn="" android:textOff=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shuffle_button" />
...

res/drawable/shuffle_button.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- use "@android:drawable/btn_default" to keep consistent with system -->
    <item android:drawable="@drawable/toggle_button_background" />
    <item android:drawable="@drawable/shuffle_button_image" />
</layer-list> 

res/drawable/toggle_button_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- checked state -->
    <item android:state_pressed="f
answered 2010-05-01T19:36:38.890

Your Answer