Wednesday, 6 May 2015

Lesson 3 Using Popup Notifications ---2

Using Popup Notifications

Alerts

When I was a kid I used to love The Great Muppet Caper.  I vividly remember a scene where Gonzo shouts, “Stop the Presses!”  The editor asks him what happened and he says, “I just always wanted to say that.”  If you want a pop-up that makes sure it gets attention (whether something important happened or not) then an Alert might be just what you need.  Let’s update our Java Activity to look like this:
package com.learnandroid.helloworld;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
 
public class Hello3 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        AlertDialog helloAlert = new AlertDialog.Builder(this).create();
        helloAlert.setTitle("Half Dozen Hello Worlds Demo");
        helloAlert.setMessage("Hello World");
        helloAlert.setButton("Close", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface arg0, int arg1) {}
  });
        helloAlert.show();
    }
}
The lines we’ve added are:
        AlertDialog helloAlert = new AlertDialog.Builder(this).create();
        helloAlert.setTitle("Half Dozen Hello Worlds Demo");
        helloAlert.setMessage("Hello World");
        helloAlert.setButton("Close", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface arg0, int arg1) {}
  });
        helloAlert.show();
The AlertDialog Class makes use of the Builder Class AlertDialogBuilder.  So in the first line when we call:
AlertDialog helloAlert = new AlertDialog.Builder(this).create();
We are using the Builder to return an AlertDialog object to us that is already partially setup for our use.  The next two lines use setTitle and setMessage to set the text displayed to the user in the dialog’s title section and body respectively.  Finally, we need to have a way for the user to actually interact with our alert.  At minimum we should have a close button so the user can make the alert go away. We use setButton, passing it the text that should be displayed on the button, and an event that allows us to perform actions when the button is clicked.  By default, the dialog will be closed on a click event so we don’t need to put any code into our event.  Finally we call the show method, like we did with toast, to display our Hello World pop-up.
While that technically finishes both of our Hello World pop-up programs I want to take a moment to examine the buttons on the AlertDialog.

No comments:

Post a Comment