Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating a Button and Its Click Event Listener

In Chapter: Graphical User Interface
Author: Ian Darwin ('idarwin')
Published? true
FormatLanguage: WikiFormat


You need to do something when the user presses a Button.


Create a Button in your layout. In onCreate(), find it by ViewID. Call its onClickListener(). In the OnClickListener implementation, check for the ViewID and perform the relevant action.


Creating a Button in your layout is simple. Assuming XML layout:

<Button android:id="@+id/start_button"

In your activity's onCreate(), find the button by its ViewIDm (in this example, R.id.start_button. Call its onClickListener() method with an OnClickListener.

In the OnClickListener implementation, check for the ViewID and perform the relevant action.

public class Main extends Activity implements OnClickListener {
	public void onCreate() {
		startButton = findViewById(R.id.start_button);

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_button:
			// Start whatever it is the start button starts...
		case R.id.some_other_button:
			// etc

Any experienced Java programmer would expect to use an anonymous inner class for the onClickListener, as has been done in AWT and Swing since Java 1.1. Due to efficiency, early Android documentation recommended against this, simply having the Activity implement OnClickListener and checking the ViewID (i.e., the Java 1.0 way of doing things), As with Swing, however, the power of devices has gotten much faster, and such old-style ways of doing things are becoming less popular, though you will still see both styles in use for some time.


If you found this recipe useful, why not buy the book and have the whole collection always at hand?"