k0sh k0sh - 3 months ago 7
Android Question

Why DialogFragment is not being destroyed while Dialog is?

as the title says, why does Android keeps the

DialogFragment
open when a
configChange
happens while any type of
Dialog
is being destroyed as soon as there is a
configChange
? is it because the
Android
doesn't want to keep a reference to the
Context
passed to the
Dialog
? if so, then how they actually keep surviving the
DialogFragment
while
configChange
happened?

Edit : i do know that the
dialogFragment
is being recreated, why don't they do the same to
Dialogs
as well?

Answer

Okay, after i dig-in into the source code of the DialogFragment i found out that its just a Fragment that handles configChanges by savingInstance of the current Fragment and re-create it on Orientation Changed.
When we actually call dialogFragment.show(getSupportFragmentManager(),TAG) the Framework create a Fragment that handles Dialog lifeCycle for example

@Override public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        mStyle = savedInstanceState.getInt(SAVED_STYLE, STYLE_NORMAL);
        mTheme = savedInstanceState.getInt(SAVED_THEME, 0);
        mCancelable = savedInstanceState.getBoolean(SAVED_CANCELABLE, true);
        mShowsDialog = savedInstanceState.getBoolean(SAVED_SHOWS_DIALOG, mShowsDialog);
        mBackStackId = savedInstanceState.getInt(SAVED_BACK_STACK_ID, -1);
    }
}

in onCreate method it restores the Dialog parameters that are saved within

onSaveInstanceState(Bundle outState)

and restore the dialog instance in
@Override public void onActivityCreated(Bundle savedInstanceState) {}
by calling mDialog.onRestoreInstanceState(dialogState);

so when we actually use DialogFragment the Framework save us the time by handling the configChanges that might occur while Dialogs are showing.