Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Mobile =>  Android

Android create button tutorial

  Dev Notes      2014-11-07 08:30:10      4,307    0

This tutorial assumes that you already have an activity and are using an XML layout.

Open the layout XML and add the button element.  Assign an ID with the “@+id” operator.  The + tells Android to generate an ID for this element so that you can reference it in your Java files.

This is an example. Your layout and text elements will probably be very different. In this example case, the ID of the button is “close”.

<Button android:id="@+id/close"
    android:text="@string/title_close" />

Open the activity class.  Add a class property to hold a reference to the button.

privateButton closeButton;

If you haven’t already, override the onCreate method.

protectedvoid onCreate(Bundle savedInstanceState){}

For this example, we don’t need the saved instance state, so ignore it.

Now, in the onCreate method, attach a listener to the click event for the button.  This example will call “finish()” on the activity, the Android analog of clicking the close button on a window.

protected void onCreate(Bundle savedInstanceState) {
  this.closeButton = (Button)this.findViewById(;
  this.closeButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

Here’s a short description of what’s happening.

  1. First, get the button ID.  The ID created earlier in the layout, “close”, is compiled by Android and assigned a unique integer ID which is available to the application through the “R” class, which I assume is short for “Resources”.
  2. Request a reference to the button from the activity by calling “findViewById”.  The button has to be retrieved from the activity because while an ID is unique in an activity, it is not unique among all activities.
  3. Assign the retrieved button to an instance variable so that if you need it later, you can easily find it without having to query for it again.
  4. Create a class implementing “OnClickListener” and set it as the on click listener for the button.

As UI elements go, buttons are some of the simplest.  Later, I’ll write about menus and dialogs, which aren’t so easy.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


Adapter design pattern explained

By sonic0002