Simple Example : Click on button

Explain: The application places a button to occupy the screen. When clicked the button’s text shows current time.

Create new Android Project And use this parameters :

  1. Project name : MyFirstUIAndroid
  2. SDK: Android 2.3 (because it is the most used until today), Note: you can use emulator for Android 4.0.3 to test your application if you need that.
  3. Package Name: tn.insat.houcine
  4. Create Aclivity: ButtonActivity
  5. Minimum SDK: 10

Now edit the XML File named main.xml (location : under res/layout in your project) to add a button into your layout :

 <?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”;
android:orientation=”vertical” android:gravity=”center”><Button
android:text=”MyFirstButton” />
Because we want to reference this button from our Java code, we need to give it an identifier via the android:id attribute.

  • android:text indicates the initial text to be displayed on the button face (in this case,an empty string).
  • android:layout_width and android:layout_height tell Android to have the button’s width and height fill the “parent“ container, in this case the entire screen or wrap the content that the button need.
Best Practices:
you can change the button name with a link to an attribute into an xml file (located under res/values) that contains only a Strings,Colors, Lists,… because it will centralize the changes of text, title or color into a single place and facilitates the internationalization of your application later.
Now, change the java Class (Named: ButtonActivity) to load the button and add a Click Event to allow the user to chow The date and time after clicking the button.
package tn.insat.houcine;

import java.util.Date;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class ButtonActivity extends Activity {
Button btn;
public void onCreate(Bundle savedInstanceState) {
btn = (Button) findViewById(;
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
private void updateTime() {
btn.setText(new Date().toString());
Now to test this application right click on the project and select Run As then select Android Application.

2 comments on “Simple Example : Click on button

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s