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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: watch movies online()

  • Pingback: free movie downloads()

  • Pingback: free movie downloads()

  • Pingback: Blue Coaster33()

  • Pingback: Google()

  • http://inmanlee.tk:25000 Kiwi

    Really helpful. Thanks.

    • skew

      Actually no, completely useless.

  • http://www.cube99.com/users/RandallDe 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 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.

  • http://android.programmerguru.com 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/

  • http://anitoanisioanisiamto.org Daron Bourjolly

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

  • Akshat

    Excellent. Working Perfect.

  • Imrankhan

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

  • Abilash

    Its useful

  • http://www.kickstarter.com/profile/frownwasher1 Alejandrina

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

  • http://yahoo.com Stacey

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

  • http://google.com 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.

  • http://yahoo.com popular internet search terms

    Yes! Finally someone writes about google ranking.

  • http://google.com 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

  • http://google.com/ 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 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

    Good Example !! Thank u :)

  • http://hohl.swissblog.ch/trinkspiel/ 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 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.

  • Pingback: How To Open An URL In Android’s Web Browser « JAVAPAGES 4 ALL()

  • 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 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.

  • 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

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

      • http://www.encodedna.com 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

  • fabio

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

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

  • Shawn

    Is anyone else getting a dialog popping up “Complete Action Using…” and the browser doesn’t launch in the emulator? Why is that happening and how does one fix it? Thank you!

  • http://henrocker01.weebly.com Henrock

    Nice , thank you!

  • Gowtham Raj

    Hi.. I am new to Android.. This Tutorial Make me too feel Android is easy…

  • bruce

    its not working yeah!

  • http://nonr sameer

    I hwant develop simple application in Java Eclipse android .here i required to develop single application required user Interface are Text View , Password and Button after submit Next Page moved and displayed message. next another control click move to previous page .

  • Prathap

    Thanks for share this…its really helpful for fresher android developer…

  • http://teleiasolutions.com Jeff Teleia

    Great article thanks!

  • Sandeep Reddy

    After Click the button i got some msg like this

    The Application xxxxxx has stopped unexpectedly.Please try again.

  • Sriharsha

    Hi !! Mkyong , nice and lucid example on Button Listener. Worked like a charm :) Modified the above code by adding a toast event and sleepFunction just before Intent is started.. Keeping posting such nice lovely examples :)

  • sitara khan

    kindly send me a perfect email address for contact

  • sitara khan

    i m doing a project on android but i m just not able to understand coding for button kindly send me a e-mail for complete of button and text field and there connectivity in android

  • Rey Andy

    ========================================

     @Override
    			 public void onClick(View arg0) {
     
    			  Intent browserIntent = 
                                new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;http://www.mkyong.com&quot;));
    			    startActivity(browserIntent); 
    .......

    ======================================
    hello mkyong….i tried the code you have presented,,above…but there is an error in the @Override before the onClick() method…but when i deleted the @Override ..i can execute the program successfully…why is this so?…pls enlighten me….tnx

  • John

    What needs to be done with the above code in AppActivity.java file to implement multiple buttons? I can’t seem to get more than one button to work. Thanks.

  • tanu

    new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.mkyong.com”));
    i think the action need to ACTION_WEB_SEARCH…otherwise the activity dose not start

  • Glenview Jeff

    addListenerOnButton() should be a private method, not public.

  • Pingback: How to open an URL in Android’s web browser()