Saturday, 3 November 2012

Android Custom Button Example




Android provides default UI Button for button view.But sometimes we need better UI for application and new colorful button rather than default.so we need to create nice UI for button which looks awesome with application design.

 First you add button in your xml layout file.Then create xml in drawable folder for button background.

in xml drawable file add selector for button.

then add item tag for button state.which has different state like state_pressed,state_focused,state_enabled.

So here we used only state_pressed and check its true or false,then we add other property for both state

now  create two <item ></item> tag and put condition state_pressed or not.

After we can set corner radius for button and when we set radius its looks like rounded box.

Now we have <solid> tag for button inner color.so you can set color for both state.

Using <padding> tab you can put inner spacing.and its considering space from corner of button,

And the last tag is <stroke> which is used for rounded colorful border.and you can set thickness of border using width and its have color also for colorful border.

Now just set your button background in xml layout flie.

 android:background="@drawable/btn"
 
So using below code you can create custom and if you want to set other color select your hex string and past in android:color in solid tag.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape android:shape="rectangle">
            <corners android:radius="10dp" />

            <solid android:color="#0c76ab" />

            <padding android:bottom="10.0dip" android:left="10.0dip" android:right="10.0dip" android:top="10.0dip" />

            <stroke android:width="1.5dip" android:color="#222" />
        </shape></item>
    <item android:state_pressed="false"><shape android:shape="rectangle">
            <corners android:radius="10dp" />

            <solid android:color="#d9d9d9" />

            <padding android:bottom="10.0dip" android:left="10.0dip" android:right="10.0dip" android:top="10.0dip" />

            <stroke android:width="1.5dip" android:color="#222" />
        </shape></item>

</selector>



Download Full Source Code