Android button example

In Android, just use “android.widget.Button” class to display a normal button.

In this tutorial, we show you how to display a normal button, add a click listener, when user click on the button, open an URL in your Android’s internet browser.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

Note
For more advance function, like image, please refer to this ImageButton example and also this ImageButton selector example.

1. Add Button

Open “res/layout/main.xml” file, add a button.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button - Go to mkyong.com" />
    
</LinearLayout>

2. Code Code

Attach a click listener to the button.

When user click on it, open mobile browser and display URL : http://www.mkyong.com.

File : MyAndroidAppActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends Activity {

	Button button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		addListenerOnButton();

	}

	public void addListenerOnButton() {

		button = (Button) findViewById(R.id.button1);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			  Intent browserIntent = 
                            new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.mkyong.com"));
			    startActivity(browserIntent);

			}

		});

	}

}

3. Demo

Run the application.

1. Result, a normal button.

android button demo1

2. Click on the button, display URL in browser.

android button demo2

Download Source Code

Download it – Android-Button-Example.zip (15 KB)

References

  1. Android Button JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Divya P
Guest
Divya P

i done a calculator program using checkbox and button. if u uncheck the add button. the result will not deleted. help me.

Alaa Zidan
Guest
Alaa Zidan

Thanks

Ooha
Guest
Ooha

how to change silent to ringer of a mobile by sending sms in adroid eclipse

Zubair
Guest
Zubair

I have write this lecture about Buttons and its click events . please check this.

http://themasterworld.com/button-and-its-click-events-in-android-studio/

Ragib Ahsan
Guest
Ragib Ahsan

thanks

Philip Jeffrey Trowe
Guest
Philip Jeffrey Trowe

Check out my blog. The following post includes a video
that shows you how to create an Android smartphone application that displays a
vertically scrolling list of countries on the screen. The application is
created using the Eclipse IDE and Android SDK. It features an “OK” button at
the bottom of the screen that, when pressed, terminates the application.

In the process of making this Android application you will
encounter the following SDK object types, etc: ScrollView, Button, View, TableLayout, TableRow, OnClickListener, TextView, and Colours in Android represented by hexadecimal numbers.

http://androidprogrammeringcorner.blogspot.com/2015/03/pak-longs-android-programming-corner.html

Best regards,

Philip

Chathura Wijesinghe
Guest
Chathura Wijesinghe

Find most useful Android Button Libraries and Resources from http://android-libs.com/search/buttons

Manu Kushwaha
Guest
Manu Kushwaha

how to connect button to the text file?

Arshyan Ahmed
Guest
Arshyan Ahmed

Helpful.. (Y)
[Software Engineering.. Its Worth]

Nabajit Paul
Guest
Nabajit Paul

its a really a good eg.But when i click on button(“Button – Go to mkyong.com” ) its shows all browser of my android mobile which is different browser installed previously.But i want to open website in this form automatically instead of showing the browser list.So what should I do…..Please help.

Basil
Guest
Basil

When i run the code in emulator,i got error of “process stopped unexpectedly,Please try again”

Kiwi
Guest
Kiwi

Really helpful. Thanks.

skew
Guest
skew

Actually no, completely useless.

Jenni
Guest
Jenni
I would like to express my thanks to the writer just for rescuing me from this particular circumstance. Right after looking out throughout the the net and obtaining notions which are not powerful, I assumed my life was over. Existing without the strategies to the problems you have solved by way of your good short post is a critical case, as well as the ones that would have negatively damaged my career if I had not encountered your blog. Your own personal competence and kindness in taking care of all things was valuable. I’m not sure what I would have… Read more »
Android Guru
Guest
Android Guru

How to check whether Wi-Fi internet access is active or not in a device. Take a look at the post:
http://android.programmerguru.com/android-check-wifi-internet-connection/

Daron Bourjolly
Guest
Daron Bourjolly

Real good in sequence can be present bring into being resting on this blog.

Akshat
Guest
Akshat

Excellent. Working Perfect.

Imrankhan
Guest
Imrankhan

what is the android coding for go to website when clicking the application icon

Abilash
Guest
Abilash

Its useful

Alejandrina
Guest
Alejandrina

Hi, of course this paragraph is actually good and I have learned lot of things
from it regarding blogging. thanks.

Stacey
Guest
Stacey

Very shortly this web page will be famous among all blogging viewers,
due to it’s fastidious posts

google.com
Guest
google.com

Appreciating the dedication you put into your site
and in depth information you provide. It’s good to come across a blog every once in a while that isn’t the same
outdated rehashed material. Fantastic read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

popular internet search terms
Guest
popular internet search terms

Yes! Finally someone writes about google ranking.

internet marketing search engine placement
Guest
internet marketing search engine placement

Nice blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple adjustements would really make my blog shine.
Please let me know where you got your design. Thank you

Delores
Guest
Delores

When I originally commented I clicked the “Notify me when new comments are added” checkbox and now
each time a comment is added I get three e-mails with the same comment.
Is there any way you can remove people from that
service? Cheers!

http://bing.com
Guest
http://bing.com

Nice weblog here! Also your website so much up fast! What host are you the usage of?
Can I am getting your affiliate hyperlink for your host?
I desire my site loaded up as fast as yours lol

Arvind
Guest
Arvind

Good Example !! Thank u :)

Moises
Guest
Moises
As we all know, looks can be deceiving, so I decided to try out the question tool for myself. Once the number of back links will increase, web traffic flow will enhance. The more doors you have the more chances of people finding it. This can be a great tool when selling products online, as a website can be designed to offer either luxury or bargain-oriented goods, based on traffic analysis. SEO must be implemented by following a step by step process. Enough said. Since keyword analysis is needed for both SEO (search engine optimization) and SEM, we often confuse… Read more »
trackback
How To Open An URL In Android’s Web Browser « JAVAPAGES 4 ALL

[…] Note For full example, please refer to this – Android button example. […]

Paulo Carrillo
Guest
Paulo Carrillo
Hi, how are you? Firstly, I like all your tutorials I see, it’s easy to understand everything. Secondly, I saw some examples of primefaces on your web, i don’t know if you have some tutorial with primefaces mobile, it would be very helpful. I will thank you if you can do it. Another thing i wanted to ask you is: Have you ever seen a NoSuchFieldError Exception?, I like to call some persistence methods from a hibernate project into a primefaces mobile project (both with maven configuration) and i got this exception. Persistence Project works well and primefaces mobile project… Read more »
hisham
Guest
hisham

i copied and pasted this over the one that was there

and then copied an pasted this one over the main java

package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends Activity {

Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

addListenerOnButton();

}

public void addListenerOnButton() {

button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.mkyong.com”));
startActivity(browserIntent);

}

});

}

}

and when i install it only says hello world!
help please

billy
Guest
billy

in the graphical layout you have to drag to make the button you can not just copy the code.

arun
Guest
arun

I agree with billy. You cannot just copy and paste the codes in “Eclipse SDK”. Just go to “res” -> layout -> and select activity_main.xml. At the bottom of the .xml file you will see 2 tabs. To drag and drop a button, go to the “Graphical Layout” section and in the “Form Widgets” palette you will find the “button” and other controls. Double click the button and write your code.

Regards

Arun