Wednesday, March 24, 2010

Custom Buttons on Android

The default buttons are a kind of ugly when you change the background of an activity. In some scenarios, you will be forced to change the way your Buttons look. To achieve this, you need not create your own custom Button class. The Android framework provides ways to achieve this with minimum effort.


Let's say we have a Button in a simple layout for which we need to do this. Here is a simple layout with just a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/click"
    android:background="@drawable/custom_button"
    />
</LinearLayout>
Note the android:background attribute on the Button. This refers to a drawable which is an xml in your drawable folder which will determine the different states of your button, namely,
1. default
2. pressed
3. focussed

This is the code for custom_button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/focussed" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/focussedandpressed" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pressed" />
    <item android:drawable="@drawable/default" />
</selector>

For this selector tag, note all the drawable attributes. You will have different png images for each of the states which you would put in your drawable folder.

Now you have your own custom button with customized look and feel.

6 comments: