How can I make make a border for a clicked imagebutton in Android?

user2426316 picture user2426316 · Feb 18, 2014 · Viewed 15.1k times · Source

I am using Imagebuttons to show some icons in my android project.

<ImageButton
    android:id="@+id/button_one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:padding="20dp"
    android:contentDescription="@string/button_one"
    android:background="@android:color/transparent"
    android:src="@drawable/button_one" />

I would like, when the button is in pressed state, there to be a white border with rounded corners. What can I do to make this happen? Can this be done using just code or will I need an extra background image?

Answer

singularhum picture singularhum · Feb 18, 2014

Here's one way if you don't want to create separate images with a border.

Create a drawable xml with your border style (ex. border.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="#FFF" />
    <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    <corners
        android:bottomRightRadius="8dip"
        android:bottomLeftRadius="8dip"
        android:topRightRadius="8dip"
        android:topLeftRadius="8dip" />
</shape>

Create a selector drawable (ex. some_selector_name.xml). Basically when pressed, it will show your border drawable. Otherwise, it will be transparent.

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

Set your image button's background to your selector drawable.

<ImageButton
    android:id="@+id/button_one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:padding="20dp"
    android:contentDescription="@string/button_one"
    android:background="@drawable/some_selector_name.xml"
    android:src="@drawable/button_one" />

Now when you press the button, it should display the white border. This is just an example but you should get the idea.