Thursday, March 8, 2012

Displaying an AlertDialog

An alert dialog creates a popup message with options like "Yes" or "No" and allows the developer to give functions to each option. In this tutorial you will learn how to create your own AlertDialog.

  • First you must declare the AlertDialog
AlertDialog alertDialog = new AlertDialog.Builder(YourActivityName.this).create();

  • If you would like to give your AlertDialog box a title include the code alertDialog.setTitle("Your Title");
  • Give the box a message by setting the text to alertDialog.setMessage("Your message");
  • Now create the buttons will be displayed and add any functions.
alertDialog.setButton("Yes", new DialogInterface.OnClickListener(){


     public void onClick(DialogInterface dialog, int which) { 
           //add functions here


            }

      });
  • If you're creating a second button use the same code but replace .setButton with .setButton2.
  • If you would like you can set an icon for your AlertDialog with the code alertDialog.setIcon(R.drawable.youricon);
  • Finally in order to show your dialog, use the code alertDialog.show();
alertDialog.setButton("Yes"new DialogInterface.OnClickListener() {

         public void onClick(DialogInterface dialog, int which) { 
               //add functions here


                }

          });
          alertDialog.show();


    No comments:

    Post a Comment