Android highlight an imagebutton when clicked

Droidme picture Droidme · Mar 16, 2011 · Viewed 40.5k times · Source

I am using an ImageButton. But I don get the highlight when clicked. I googled and many suggested to use selector where another image is displayed. Is there any way around this. by using only one image and highlighting it or giving it a glow effect. so that the user knows that button has been clicked.

Answer

Zack Marrapese picture Zack Marrapese · Mar 16, 2011

This is actually not very difficult to do. You don't even need to create 2 seperate .png files or anything like that. For instance, if you want to have a button which has a gradient, and then change it when the button is pressed:

Step 1: Create default button gradient (drawable/default_button.xml):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <corners android:radius="3dp" />
    <gradient android:endColor="#8ba0bb" android:startColor="#43708f" android:angle="90" />
    <stroke android:width="1dp" android:color="#33364252" />
</shape>

Step 2: Create default button pressed gradient (drawable/default_button_pressed.xml):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <corners android:radius="3dp" />
    <gradient android:endColor="#43708f" android:startColor="#8ba0bb" android:angle="90" />
    <stroke android:width="1dp" android:color="#33364252" />
</shape>

Step 3: Create selector (drawable/default_button_selector.xml):

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/default_button_pressed" /> 
    <item android:drawable="@drawable/default_button" /> 
</selector>

Step 4 (optional): Create style for the button (values/style.xml):

<resources>
    <style name="DefaultButton">
        <item name="android:layout_width">wrap_content</item>   
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/default_button_selector</item>
    </style>
</resources>

Step 5: use the button (layout/main.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" android:layout_height="fill_parent">

    <button style="@style/DefaultButton" />

</RelativeLayout>

As you can see, it's not particularly difficult to do.