user45678
user45678

Reputation: 1514

How to have a pressed-state in button without using image

I have a ImageButton for which i have only one png icon as shown in screenshot. Now I want to have a "pressed-state" of it without having another image. Can this be done by using color selector, if yes how can it be done using transparent thing so that image remains only but there would be two pressed state ?

Code :

<ImageButton
            android:id="@+id/syncbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginTop="3dip"
            android:background="@android:color/transparent"
            android:gravity="center"
            android:text="Sync"
            android:src="@drawable/sync"/>

Upvotes: 0

Views: 73

Answers (1)

Sound Conception
Sound Conception

Reputation: 5411

You're on the right track already.

Use a custom drawable for your background instead of "transparent" for your ImageButton:

<ImageButton
            android:id="@+id/syncbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginTop="3dip"
            android:background="@drawable/my_highlight_drawable"
            android:gravity="center"
            android:text="Sync"
            android:src="@drawable/sync"/>

The my_highlight_drawable is just a color selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@color/my_pressed_highlight_color"
        android:state_pressed="true" />
    <item android:drawable="@android:color/transparent" />
</selector>

Basically you can think of an ImageButton as a normal button but with two image layers.
android:background defines the bottom layer and android:src defines the top layer. You can use all the same drawable types like bitmaps, selectors, Nine-Patch, shapes and so on, on both layers.

Upvotes: 1

Related Questions