Coding for Android Button Clicks

Android Activities: 1 2 3 4 5 6 7 8

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 MainActivity.java 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. You can see it at the top by expanding the import plus symbol:

The import statement

You'll then see which code libraries have been imported:

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

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.