android:onClick - Add an OnClick Action to a Button

How to Add an OnClick Action to a Button

android:onClick was added in API Level 4

Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.

 1. Add a button to your layout.

 2. Ensure to change the minSDKVersion to 4, or greater. If you are targeting API Level 3 and under, you can use setOnClickListener for creating a Click Handler for a Button, using a method instead.

 3. In the MainActivity.java file, add this import to the import section.

            import android.view.View;

 4. Add a new method called onClickmyButton. (Must be set to public and not private.)

public void onClickmyButton(View v) {
// your onClick code goes here //Add a toast to test it.
}

5. In the main.xml file, add the highlighted code between the <Button> tags.

  <Button
        ...
       android:onClick = "onClickmyButton"
  />

6. Compile and run! Press the Button to test!

Next Recommended Article: Name a Button

Related Articles:
Resources: