Android create button tutorial

  Dev Notes        2014-11-07 08:30:10       5,994        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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    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.

@Override
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.setContentView(R.layout.layoutxml);
  this.closeButton = (Button)this.findViewById(R.id.close);
  this.closeButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      finish();
    }
  });
}

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.

ANDROID  SIMULATOR  BUTTON  XML  TUTORIAL 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

PM vs Programmer