Coding for Android Button Clicks

In the previous lesson, you created a screen with a label and a button. What we'll do now is to add a method to the Java class. This method will be called when the button is clicked.

Open up your file. Type the following method just below the OnCreate one:

public void displaySecondActivity( View view ) {


Your coding window will look like this:

Android Java code for a method

Notice the red View between the round brackets of displaySecondActivity. It's red because Android needs to imports some code that recognises what a View is (a View is just things like buttons, TextViews, Checkboxes, RadioButtons, etc). Hold down the ALT key on your keyboard. Keep it held down and then press the Enter key. Android Studio will import the correct code for you. If you see a popup instead, select Import Class from the menu:

Importing the View class in Java

You can see the import line at the top by expanding the import plus symbol:

The import statement

You'll then see which code libraries have been imported: (Later versions of Android Studio will import as the first line.)

Importing the Android View.

Once the android.view.View code library has been imported, the red View from your method should turn the correct colour. (If ALT + ENTER doesn't work for you, simply type the import statement at the top of the code.)

We'll add code for the method shortly. But now let's get the button on the Activity layout to recognise our new method.

Click back on the activity_main.xml tab at the top of the designer. Click your button to select it. Now locate the onClick item in the properties area on the right:

The onClick property in Android Studio

Or this one, in later versions of Android Studio:

The onClick item in the Common Attributes section

Click the dropdown box to see a list of available methods you can use for your button clicks:

Selecting a method to use for onClick

We've only created one method, displaySecondActivity, so select that:

A method set for onClick

The text on the button is Show Activity Two, and the method that will be called when the button is clicked is displaySecondActivity.

Now that Android recognises an onClick method for the button, we'll add something called an Intent to the code. This will be used to display a second Activity.

Back to the Android Contents Page