Android SDK Tutorial: Button onClick Event

Making your app notice when a button was clicked is pretty simple, the code am giving you here is what I found to be the shortest method to do so.

The Result

We will make a button that updates a label with the current date when you click it. Pictures below.

button and text before button was clicked

The app before a button click


Now when you the click button:
Text showing current date. There is also a click me button.

After the click: the text was updated to the current date.

The Button Click Class (HelloAndroid.java)

package com.example.helloandroid;

import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class HelloAndroid extends Activity{
	TextView date;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		date=(TextView)findViewById(R.id.dateText);
	}
	
	public void showNewDate(View v)
	{
		date.setText(new Date().toString());
	}
}

The Android Manifest(AndroidManifest.xml)

Don’t forget to change android:minSdkVersion to the version you are using.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.helloandroid"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
    
        <activity android:name=".HelloAndroid"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

The Layout(main.xml)

The line android:onClick is saving us from typing many more JAVA code lines. The value is the method in the JAVA file we want to execute when a user clicks the button.

<?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">
	<TextView 
		android:text="You haven't clicked" 
		android:id="@+id/dateText" 
		android:layout_width="wrap_content" 
		android:layout_height="wrap_content" />
	<Button
	    android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Click Me"
	  	android:onClick="showNewDate"/>
	
</LinearLayout>