Will AlertDialog vanish?


#1

The book is excellent in the design and explanation of creating an AlertDialog in Chapter 12. In Chapter 12 you mention “a bare AlertDialog will vanish if the device is rotated”. I am assuming you had some case(s) in mind.

Can you explain or give more detail on the vanishing AlertDialog case(s)?

Because, when I run API Demos from version 10 on my 2.3.4 and version 17 on my 4.2.x devices, none of the many examples of AltertDialog vanish if the device is rotated.

PS: Of course I sometimes see bad code on StackOverflow (and others) and complaints of vanishing AlertDialog. LOL


#2

Our wording in this passage is a little unclear. By a “bare” AlertDialog, we mean something like the following code by itself:

// Never write this!
new AlertDialog.Builder(getActivity())
    .setTitle(R.string.date_picker_title)
    .setPositiveButton(android.R.string.ok, null)
    .show();

This is a “bare” AlertDialog - it is created and shown without any other support code. Without any other mechanism to recreate the dialog when the enclosing activity recreated, this dialog will disappear on rotation.

Of course, sometimes the ApiDemos code doesn’t use DialogFragments, either. You will notice, though, that it always constructs AlertDialogs inside the onCreateDialog(int) method:

    @Override
    protected Dialog onCreateDialog(int id) {
        ...
    }

This is one part of an older deprecated API called managed dialogs. This API is easier in some ways than DialogFragments (you don’t have to fiddle with target fragments or onActivityResult), but in other ways it is less flexible. It doesn’t accomplish the exact same thing as DialogFragment, but it does solve the rotation issue we describe.


#3

Great information. Thank you.