Friday, February 6, 2009

Android 101: Launching dialogs - part 1

Hello!  We're going to talk today about a common task in Android, and user interfaces in general - launching a dialog to retrieve data.  
If we want very simple information, such as an OK/Cancel or Yes/No, we can use AlertDialog.  The code would look like this:
new AlertDialog.Builder(this)
     .setMessage("Should I buy a new cell phone?")
     .setPositiveButton("Yes", myClickListener)
     .setNegativeButton("No", myClickListener)
     .show();
It often makes more sense to implement OnClickListener in the class that's launching the dialog so that the data is sent to the object that launched the dialog.  Here's how that generally looks:
public class MyDialog extends Activity implements OnClickListener{
...
public void foo()
{
 new AlertDialog.Builder(this)
      .setMessage("Should I buy a new cell phone?")
      .setPositiveButton("Yes", (OnClickListener)this)
      .setNegativeButton("No", (OnClickListener)this)
      .show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
// "which" contains the result of the alert dialog
}
}
Execution passes from foo() to the AlertDialog.  When the user presses "Yes" or "No", the dialog is closed and onClick() is called.  From there, we can update object members and take other actions based on the results of the dialog.  It's a pretty straightforward mechanism once you watch it work, and it's a useful way to keep from writing tons of tiny classes that are tightly coupled.
Part two will talk about how to return multiple variables from a dialog using Bundle and Intent.

No comments: