Android Button Example- How to add button in android application.

Button is a very common component in user interface.You can write text or put any icon on button so user can understand what action occurs when they press or touches it.
In Android programming to display a normal button “android.widget.Button” class is used.
I will show you, How to add button in android application and the use of click listener. When user touches the button then the URL which is written in “onClick listener” opens in a default browser.
Now, the steps for creating this application are :

  1. Design your UI in .xml file.
  2. Create a java file.
  3. Add onClick listener in java file.

Your activity_main.xml file :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android=""
android:orientation="vertical" >

android:text="Button - Go to" />


Once you Design your UI in “activity_main.xml” file, Write your code in “” file.

Your file:

package com.example.button;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

Button button;

protected void onCreate(Bundle savedInstanceState) {

private void addListenerOnButton() {
// TODO Auto-generated method stub

button = (Button) findViewById(;

button.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse(""));




public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == {
return true;
return super.onOptionsItemSelected(item);

Now run it as Android application.

 Here is the first view of applicatin :

Now, This is second view of application when you touches the button.

Leave a Reply