Responding to Click Events
When the user clicks a button, the Button
object receives an on-click event.
To define the click event handler for a button, add the android:onClick
attribute to the <Button>
element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.The Activity
hosting the layout must then implement the corresponding method.
For example, here's a layout with a button using android:onClick
:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
Within the Activity
that hosts this layout, the following method handles the click event:
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
The method you declare in the android:onClick
attribute must have a signature exactly as shown above. Specifically, the method must:
Using an OnClickListener
You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button
at runtime or you need to declare the click behavior in a Fragment
subclass.
To declare the event handler programmatically, create an View.OnClickListener
object and assign it to the button by calling setOnClickListener(View.OnClickListener)
. For example:
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});