Search This Blog

Friday 20 July 2012

Creating alerts

In this post we will learn how to create alerts.  You can see an example of an Alert Dialog in my Maths Test App (If you have not already downloaded it, then locate the Maths Test App by searching the Android Market / Google Play for "Sundev Pabla").

In the Maths Test App I use an alert to inform the user if they enter a game duration of less than 10s - originally all I wanted to do was handle the situation where the  user enters a null duration but then I decided to force the user to play for a minimum of 10s.  In order to set the Game Duration press the menu button before starting the game and select 'Set Game Preferences'.  The following code extract is taken from my Maths Test App:


            if (cUserPreferences.gameDuration < 10)
            {
            AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
            builder.setTitle("Warning")
            .setMessage("You entered a game duration of less than 10s. Your game duration has been defaulted to the minimum value of 10 seconds.")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {
                  cUserPreferences.gameDuration = 10;
                 }
              });
          AlertDialog alert =builder.create();
          alert.show();
         
            }

In the above extract I first check if the user has entered a game duration of less than 10 (If the user entered a null duration then I have already set the game duration to zero in order to force entry into the if block).  In the if block I create an instance of the AlertDialog.Builder class and use it to set the title of my alert dialog to "Warning", I then also use it to set the message I want displayed to the user.  The builder  is also used to create an ok button with a button click listener.  When the user clicks the "OK" button I set the game duration to 10s.  Finally I use the builder to create my alert dialog and then call show on the alert dialog.

I think this is enough for today, I will leave you to have a play with Alerts and next time we will look at displaying custom dialogs to the user (like  the one I use to get user preferences in the Maths Test App).

All the best until next time.

No comments:

Post a Comment