A button is a GUI component that can listen for events and respond to them using callback code.
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
// Register the button
final Button button1 = (Button) findViewById(R.id.button_id);
// Set the button's on click listener
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
}
Explanation of the button's click handler
package name: android.view
"Provides classes that expose basic user interface classes that handle screen layout and interaction with the user."
View.OnClickListener
Interface declared in the above package for some arbitrary code to run when the view is clicked. The interface has one abstract method: public void onClick(View v).
Use the new operator to instantiate an anonymous class that implements the View.OnClickListener interface and pass that object to the button1.setOnClickListener method.
The publicvoid onClick(View v) is an abstract method declared in the View.OnClickListener interface. You need to implement it by providing it some code to run when the view is clicked.
Alternative method
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
// Implement the OnClickListener interface's abstract method by providing it some code to run.
public void onClick(View v) {
// do something when the button is clicked
}
}
See:
http://developer.android.com/reference/android/view/package-summary.html
http://developer.android.com/reference/android/widget/Button.html
http://developer.android.com/guide/topics/ui/controls/button.html