Till now, we've built static layouts that contain textviews and buttons. But when the user presses a button, nothing happens. This lesson, we're going to change that. We are going to learn how to respond when the user presses a button.

Here's the big picture on what we're going to do: When a button is pressed, we want to run a method (also called a function). A method is something that contains a block of code. This block of code will run, doing something that we want it to do.

Open a new project with an Empty Activity.

Add a button to the layout. Have a look at the previous week's lessons if you are trying to figure out how to do this. Your button might look like this:

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Your height and width might be different, and you might have other layout attributes. This is okay. Just make sure the button is visible, and can be clicked.

Add a new attribute called onClick, like this:

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="buttonClick"/>

This means that when the button is clicked, it is going to run a method named buttonClick. This method name can be anything you want.

Run the app, and try to click the button. What happens?

The app crashes. If we want to know more about why this happened, we need to look in the console. At the bottom of your IDE, there should a tab called Android Monitor. Click it to open the console.

You should see several lines in the console. Some of the earlier lines in black (if any) might just be debug output. The last few lines should be in red. This is the error output. When your app crashes, this is what you need to look for to figure out what happened.

We will learn how to interpret the error output as we go through the course. For now, start at the first red line, and keep reading till you hit something that is understandable in English. You should see something like: "java.lang.IllegalStateException: Could not find method buttonClick(View)". Like the message says, the crash was because your app could not find the buttonClick method. This makes sense: we haven't written that method yet!

Let's fix that. Head over to MainActivity.java. Type out the following function inside MainActivity (but outside onCreate).

public void buttonClick(View v) {

}

This is how you define a new method. There are many new terms in that block of code, and we will understand them next week. For now, just copy this exactly. Notice that buttonClick is the name. It can be something else if you wish, as long as it is one word without spaces. Also notice that this starts a block of code (which is currently empty).

The word View will be highlighted in red, indicating an error. This is because we need to import the View library if we want to work with Views, such as buttons. Add the following line to the top, near the other import statements:

import android.view.View;

An easy way to add missing imports is to bring your cursor to the highlighted word. A tooltip should pop up with the shortcut needed to automatically add in the import. On Mac this is option-enter, on Windows this is alt-enter.

MainActivity.java should now look something like this:

package com.example.kannan.testapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View v) {

    }
}

Run the app again and click the button. It should no longer crash, since there is now a method with the name it is looking for. If you still have a crash, review the earlier steps and check if you have any typos (including capitalization).

Our button still doesn't do anything. This is because buttonClick is empty. Let's learn our first bit of Java code, so we can actually do something. Type the following inside of buttonClick:

Log.d("MainActivity", "hello!");

buttonClick should now look like this:

public void buttonClick(View v) {
    Log.d("MainActivity", "hello!");
}

Run the app, and click the button. If you have the console open, you should see something.

Log.d is a function that lets us print debug messages to the console. This is very useful as you work on your app. When you have a complicated piece of code, it can be difficult to keep track of what is happening inside. This is especially true when something breaks. Debug messages give us a way to display information from inside the code to the console. We will be using this as we learn more Java.

Let's break down that line a bit. Log.d is the name of the method, and it has brackets. Inside of the brackets, there are two bits of text in quotation marks, separated by a comma. The first bit of text is the debug tag. This lets us identify where the debug message is coming from. Make sure this is something useful like the name of the file you are in, or the name of the method you are in. The second bit of text is the debug message. This can be whatever you wish to output. Keep in mind that all text needs to be inside of quotation marks.

Try: Change the two bits of text to see what changes in the console when you run the app again.

Try: Add more lines to buttonClick, to print more messages to the console. Notice that the order of messages matches your code.

Try: Add another button to the screen, and make that button say something else to the console. Try to see if you can replicate the steps without referring to the first button's code.

We've learnt our first bit of Java, and we've learnt how to respond to user input in the form of a button click.

results matching ""

    No results matching ""