Thursday 14 June 2012

Alert Dialogs



Creating alert dialogs is pretty straight-forward: you can construct an AlertDialog by using its Builder class, whose methods all return an instance of Builder, which basically means you can chain a series of method calls together.

  1. new AlertDialog.Builder(AlertDialougesActivity.this).setTitle("Test Dialog").setMessage("This is just for Testing..!").setNeutralButton("Close", null).show();
Would produce this alert: 

 

Here we are accessing AlertDialog’s static Builder class and handing it the context where the dialog will be displayed. setNeutralButton(String, OnClickListener) creates a button with the specified title and OnClickListener to handle anything that should happen on a click. You can simply give it a value of null because AlertDialog buttons always close when clicked; your OnClickListener would simply handle additional, custom instructions.
We have three types of buttons :

  1. setPositiveButton
    Describes an intended action or a confirmation, e.g. “Save” or “Yes”.
  2. setNeutralButton
    Describes a “neutral” action such as “Close”.
  3. setNegativeButton
    Describes a cancellation or simply a “No”.
It’s important to note that if you add all three of these buttons, they will be in the same order as the list above, so sometimes you might have to switch “neutral” and “negative” to achieve a desired order. So, the following snippet:

new AlertDialog.Builder(AlertDialougesActivity.this).setTitle("Test Dialog").setMessage("This is just for Testing..!").setNegativeButton("Cancel", null).setPositiveButton("OK", null).setNeutralButton("No", null).show();
Would produce this alert: 

 
And always remember to create at least one button so your dialog can be closed, otherwise you’ll have frustrated users seeing this:
Finally, another popular method is setIcon(int resourceId). It should be self-explanatory:
new AlertDialog.Builder(AlertDialougesActivity.this).setTitle("Test Dialog").setMessage("This is just for Testing..!").setIcon(R.drawable.ic_launcher).setNeutralButton("Close", null).show();
Would produce this alert: 

 









No comments:

Post a Comment