Skip to content

Half Dozen Hello Worlds Part 3 – Using Popup Notifications

This is part 3 of a multi-part series that looks at some basic Android I/O using simple Hello World programs. At this point I’ll assume you know how to make a new Android Project in Eclipse as that was covered in Part 1.  In this part we are going to look at two types of pop-up messages that allow you to communicate with the user outside of the normal program flow.


Imagine you are at a large dinner party.  You want to make a toast to your host.  You raise your glass a call out a toast.  Half the people at the party don’t notice (none of the kids at the kids table notice at all), but you aren’t worried about that as you clink glasses with the dozen people who did notice.  The first pop-up we are going to look at is Android’s Toast, which does exactly this.  It allows you to present a message to the user without any confirmation that they noticed the message.  Build a new project using Android SDK 1.1 and update your Activity Java to look like this.

package com.learnandroid.helloworld;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;
public class Hello3 extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        Toast helloToast = Toast.makeText(this, "Hello World", Toast.LENGTH_LONG);
        helloToast.setGravity(Gravity.CENTER, 0, 0);;

The first line of code we added to the default code generated by the project was this.

Toast helloToast = Toast.makeText(this, “Hello World”, Toast.LENGTH_LONG);

This line of code calls the Static method makeText of the Toast class.  The makeText method returns a Toast object that will display the message you provide, in our case “Hello World”, for the duration you specify.  The two available durations are Toast.LENGTH_LONG and Toast.LENGTH_SHORT.  Once we have our Toast object we can just call the show method to display it on the screen.  Before displaying our toast, however, I thought I would center it on the screen.  The setGravity method lets you tell Android where the toast should be displayed by using one of the Gravity constants, and then specifying an x offset and y offset.  Since I wanted it in the very center of the screen I used Gravity.Center and specified offsets of 0.

helloToast.setGravity(Gravity.CENTER, 0, 0);

You can see a list of available Gravity constants here.  When you run this code you should see a small pop-up with the message “Hello World” appear, and then disappear automatically without any user interaction.  On the next page we’ll look at a pop-up that requires user interaction.

{ 5 } Comments