Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a DialogFragment to not recreate after orientation change

When I'm changing the orientation of my app with a visible DialogFragment opened from my Activity, the dialog will be recreated. How can I forcefully dismiss it?

For now I tried to store it as a member in my activity and dismiss it in onCreate but at this point it seems to be null;

like image 214
adriennoir Avatar asked Sep 16 '25 02:09

adriennoir


2 Answers

To disable recreations of DialogFragments of a specific type, you can override onCreate in your derived DialogFragment class and dismiss the dialog in case it is being recreated:

public class MyDialogFragment extends DialogFragment
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null)
        {
            dismiss();
        }
    }
    ...
like image 72
wize Avatar answered Sep 18 '25 18:09

wize


As @Luksprog mentioned in the comments, a solution could be:

Give a tag to your DialogFragment at creation:

FragmentManager fragmentManager = getSupportFragmentManager();
MyDialogFragment.newInstance(...).show(fragmentManager, "myTag");

Search for it and dismiss it in onCreate

MyDialogFragment dialog = ((MyDialogFragment)getSupportFragmentManager().findFragmentByTag("myTag"));
if (dialog != null) {
    dialog.dismiss();
}

I think it would be more efficient to disable the recreation of the DialogFragment altogether but I don't know if that's possible.

like image 26
adriennoir Avatar answered Sep 18 '25 19:09

adriennoir