jueves, 4 de octubre de 2012

Android How to show dialog to confirm user wishes to exit Activity



What is the AlertDialog?

The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog class you'll need. As shown in figure 2, there are three regions of an alert dialog:

Figure 2. The layout of a dialog.
  1. Title
    This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or question (such as the dialog in figure 1), you don't need a title.
  2. Content area
    This can display a message, a list, or other custom layout.
  3. Action buttons
    There should be no more than three action buttons in a dialog.
The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of content, including a custom layout.
How to implement the AlertDialog with confirmation?

The best option to show a confirm dialog asking the user for confirmation is in the "onBackPressed" event. This event is fired when the user touch the "back" button of the device. I notice that if the user touch the "Home" button the activity is paused, but the same happens when the user uses the "back" button. The only difference is the meaning of this functionality and how do you want to react.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing Activity")
        .setMessage("Are you sure you want to close this activity?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .setNegativeButton("No", null)
    .show();
}
source: stackoverflow

No hay comentarios:

Publicar un comentario