Saturday, December 22, 2012

0 How to create custom Button in Android

From "A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it."

In this tutorial, we show you how to display a custom button with image, add a click listener by a few different ways, when user click on the button, open an URL in your Android’s internet browser.

P.S This project is developed in Eclipse 4.2.0.

Here is a result of this tutorial:
Android Custom Button- Figure 3

1. Two ways to make a button:

1.1 Design in your XML layout: 


We need file layout "button_bg.xml" in drawable folder to customize this button
File: res/drawable/button_bg.xml” 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:drawable="@drawable/up_button_press"
          android:state_pressed="true" />
    <item android:drawable="@drawable/up_button" />

Android Custom Button- Figure 1up_button.png
Android Custom Button- Figure 2up_button_press.png 
1.2. By java code
If we before have a layout like:
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android=""
Now the code we use to add button dynamically to this layout:

Button myButton = new Button(this);
// sets button properties
myButton.setText("Dynamic Button");
// btn.setId(1200);// use it if you want to set id for this button
// retrieve a reference to the container layout
LinearLayout container = (LinearLayout)findViewById(;
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// adds dynamic button to the GUI

2. Two ways to attach a click listener to the button, when user click on the button, open an URL in your Android’s internet browser
2.1. Use  android:onClick attribute in your button XML definition:

And in your code define the method button_click:

public void button_click(View view){ 
   Intent browserIntent =
             new Intent(Intent.ACTION_VIEW, Uri.parse(""));

2.2. Using an OnClickListener

myButton.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
      Intent browserIntent =
      new Intent(Intent.ACTION_VIEW, Uri.parse("http://custom-android-       "));
3.1. when start the application, the screen show two button, one created by xml layout, and one by java code
Android Custom Button- Figure 3
3.2. Click on any button, then display URL in browser.
Android Custom Button- Figure 4
You can download all source codes from here

No comments:

Post a Comment

Show Emoticons