Lesson Weekend

Now that we have our welcome page in place, or rather our MainActivity layout, let’s add some code so that our button does something when we click on it.

Navigate to java > com.epicodus.myrestaurants > MainActivity.java.

The onCreate Method

Inside of this file, we will see that there is already some code that Android Studio added when we initially created this project. For now, we only want to concern ourselves with the code inside of the onCreate() method. The onCreate() method is called every time a user visits this activity. Any code that goes inside of it will be run immediately once the activity loads.

Let’s take a closer look at the contents of onCreate():

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
  • super.onCreate(savedInstanceState); causes Android to run all of the default behaviors for an activity. It's very rare that you would change this line.
  • setContentView tells the activity which layout to use for the device screen. In this case, we are using activity_main.xml which we just styled.
  • R.layout.activity_main tells Android to use the main_activity.xml layout for this activity. R - which is short for Resources - gives us a way to access all of our files in the res directory.

Next, let’s add a member variable to hold our findRestaurantsButton so that we can access it inside all of our methods. Add the following to the top of the class to declare our Button view variable:

MainActivity.java
public class MainActivity extends AppCompatActivity {
    private Button mFindRestaurantsButton;
    …

Importing Classes

Notice that Button will turn red and underlined. This means we need to import it. In Android Studio, we can easily import elements by clicking on them and then typing Option + Enter (on our windows keyboards, try Alt + Enter ) and then clicking import class.

Adding Custom Code on onCreate

Next, let’s set our new mFindRestaurantsButton variable. Add the following code inside theonCreate() method:

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

        mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
    }

What did we just do?

  • findViewById takes the ID of the Button in our layout and returns the view.
  • R.id.findRestaurantsButton returns the view of our button.
  • (Button) typecasts our view as Button. findViewById() will return a generic type View, but our mFindRestaurantsButton was declared as the specific View type of Button, so we need to cast it as such.

Creating Click Listeners

Now that our button is set, let’s make it do something! Let’s add a click listener which will be triggered when our button is touched:

 mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
        mFindRestaurantsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do something
            }
        });

The setOnClickListener() method takes a new onClickListener as a parameter. Let’s use Tab Autocompletion to write this out. If we start typing new View and then press Tab, the rest of the code will be filled in for us.

Toasts

Inside of the onClick() method, let’s add a toast. A toast is a simple pop up message that automatically fades in and out of the screen when triggered.

A toast takes three parameters; a context, a message, and a duration. The context for our toast is MainActivity.this. We will talk in further detail about context, but for now message and duration should be pretty self-explanatory.

The resulting code should look like this:

MainActivity.java
public class MainActivity extends AppCompatActivity {
    private Button mFindRestaurantsButton;

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

        mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
        mFindRestaurantsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Hello World!", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Now let’s run our app again and we should see that our toast message appears when we click on our findRestaurantsButton:

toast-on-main-activity


Example GitHub Repo for MyRestaurants

Terminology


  • Toast: A pop up message that automatically fades in and out when triggered.

  • Context: In Android, reference to the current activity.

Tips


  • If a class name is red and underlined it means we need to import it. In Android Studio, we can easily import elements by clicking on them and then typing Option + Enter (on our windows keyboards, try Windows Key + Enter ) and then clicking import class.

Examples


MainActivity.java
public class MainActivity extends AppCompatActivity {
    private Button mFindRestaurantsButton;

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

        mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
        mFindRestaurantsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Hello World!", Toast.LENGTH_LONG).show();
            }
        });
    }
}