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

Author: Ian Darwin -- Published? true -- FormatLanguage: W

Problem:

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

Solution:

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.

Discussion:

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

<Button android:id="@+id/start_button"
	android:text="@string/start_button_label"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"/>

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);
		startButton.setOnClickListener(this);
		...
	}

	@Override
	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.

idarwin 2011-05-22 17:34:36.625 Thanks for the feedback, Eric. I'll change the paragraph now and re-do the code when I have more time.
eric 2011-05-22 17:07:45.057 I think the advice to use a switch statement is a bad choice. Many of the early recommendations from the Android team are dated already, and seem like a C programmer's perspective.