Main Tutorials

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 : https://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("https://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 Author

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

Comments

Subscribe
Notify of
55 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Divya P
7 years ago

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

Jenni
10 years ago

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 done if I hadn’t encountered such a step like this.
I am able to at this time look ahead to my future. Thanks a lot very much for the professional and amazing help.
I won’t think twice to suggest your web blog to anyone who should receive counselling on this matter.

Alejandrina
11 years ago

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

Stacey
11 years ago

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

Rahul Kumar
4 years ago

Sir can u tell how to open this url in Webview instead of browser onClick of button

Alaa Zidan
6 years ago

Thanks

Ooha
8 years ago

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

Zubair
8 years ago

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
8 years ago

thanks

Philip Jeffrey Trowe
9 years ago

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
9 years ago

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

Manu Kushwaha
9 years ago

how to connect button to the text file?

Arshyan Ahmed
10 years ago

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

Nabajit Paul
10 years ago

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
10 years ago

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

Kiwi
10 years ago

Really helpful. Thanks.

skew
10 years ago
Reply to  Kiwi

Actually no, completely useless.

Daron Bourjolly
11 years ago

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

Akshat
11 years ago

Excellent. Working Perfect.

Imrankhan
11 years ago

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

Abilash
11 years ago

Its useful

google.com
11 years ago

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
11 years ago

Yes! Finally someone writes about google ranking.

internet marketing search engine placement
11 years ago

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
11 years ago

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
11 years ago

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
11 years ago

Good Example !! Thank u 🙂

Moises
11 years ago

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 using these terms. This means that they
follow only the steps given to them by Google and
other major search engines. Isn’t that something you and your business should be a part of. What are the advantages of article submission. Use SEM experts to recognize duplicate content as part of your website, and act immediately to have it settled. However, in general, SEO services involve using standard and compliant coding. Effective SEO techniques for Bloggers aren’t any different.

It’s more control than you get In many backlinks and every element of these controls allow you to link a bit more than he would be out of control. These professionals follow ethical SEO strategy and effectively implement it that finally increases your website visibility. G) SEO basics -Image 6: Open Google. Have you been looking at your competitor’s websites to see what kind of keywords they’re using. Once someone clicks on your site, they should see tons of unique informative content. They are looking up the the keywords you did research on to find what they are looking for. SEO requires understanding of various algorithms.

Paulo Carrillo
11 years ago

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 works too, if i use persistence method into a bean from web project works well, but if i call a persistence method into a bean method and i use it into a xhtml doesnt work, i test it with an apache tomcat server. Integration Technology that i’m using is Spring.
I hope you understand me what i’m saying you and you can help me with any idea.

Moses Brodin
4 years ago
Reply to  Paulo Carrillo

“I want to be a Linux user and I tried several times but… 1.) I can’t use it to develop to iOS as it is my way to pay for my bread and milk 2.) I can’t play AAA games on it so… 3.) Many relevant softwares are missing and my laptop drivers were not fully supported (Dolby audio, Trackpad, etc)

I will stay with MacOS and Windows too. Each for their purpose. Linux has just no space for me now”
Ragerds:Moses Brodin

hisham
11 years ago

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(“https://mkyong.com”));
startActivity(browserIntent);

}

});

}

}

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

billy
11 years ago
Reply to  hisham

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

arun
11 years ago
Reply to  billy

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

fabio
11 years ago

mkyong = grande! = forte! = bravo! = grazie!

translation from Italian:
mkyong = great! = strong! = good! = thank you!