Button Click Event | Android Programming

android:onClick attribute is used to add click event to the <Button> element as below.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_submit"
    android:onClick="submitMessage" />

In the above code snippet, we have added the name of the method submitMessage to the android:onClick attribute. This method will be called when the user clicks the button.

Now, let's add the below code snippet to the respective class located in the project's src/ directory for the method submitMessage

public void submitMessage(View view) {
    // submit the changes in response to button click
}
Additional Steps
  • Import the View class: import android.view.View;
  • Method should be public
  • Method return type should be void
  • Method should have only one parameter of type View {here, it View be the view object that was clicked}