Thursday, October 4, 2012

Android: Custom round buttons

Recently working on my XBMC4Xbox Remote app, struggling with a few buttons to apply both text and a scaled image while keeping an evenly distributed layout, couldn’t get it work very well, so I gave up for now and went for an @android:color/transparent background just to move on. Then it looked a bit too bare and searched if possible to apply some borders, maybe a background colour when the button is pressed and I found that it is possible using drawable shapes.

You can create a selector and place it in res/drawable/, e.g. sel_button_round.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="rectangle" >
<stroke android:width ="2dp" android:color="#77CCCCCC" />
<corners android:radius="15dp" />
</shape>
</item>

<item android:state_pressed="true" >
<shape android:shape="rectangle">
<solid android:color ="#55CCCCCC" />
<stroke android:width ="2dp" android:color="#77CCCCCC" />
<corners android:radius="15dp" />
</shape>
</item>
</selector>

The interesting things are obviously the item definitions for each state (this is just a small sample, there are more, see documentation), the rectangle shape with solid colour to fill with, the stroke to define the line around it and then the corners with your choice of radius (the higher the value the rounder it is). Also found interesting while looking for this that you can define the alpha as part of colour definition (followed by the red, green and blue parts) - that way you can choose a colour for the borders and maybe even the fill , and then maybe the same colour but with a lighter alpha for a pressed effect, I don’t know, up to you really.

Use the selector resource as the background for the button (should work for other views, initially I had a clickable TextView), e.g. res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="3dp">

<Button
android:id="@+id/buttonOK"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="11dp"
android:text="@android:string/ok"
android:textColor="@android:color/white"
android:background="@drawable/sel_button_round" />

<Button
android:id="@+id/buttonCancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@android:string/cancel" />

</LinearLayout>

And here is the result (normal and pressed), next to a standard button.

Android, custom round button, normalAndroid, custom round button, pressed

No comments :

Post a Comment