Search code examples
androidandroid-dialogfragment

DialogFragment disappears on screen rotation


This fairly simple dialog dismisses itself after screen rotation despite I setRetainInstance to true. Any ideas whats wrong?

public class StreetDialog extends DialogFragment {

    public static StreetDialog newInstance(String[] values) {
        StreetDialog f = new StreetDialog();
        Bundle args = new Bundle();
        args.putStringArray("values", values);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final String[] values = getArguments().getStringArray("values");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //build my dialog
        return builder.create();
    }

    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance())
            getDialog().setDismissMessage(null);

        super.onDestroyView();
    }
}

Solution

  • If I recall correctly is the normal behaviour. I usually provide a tag to the show method, and when the Activity's onCreate is called again, I look for the tag. If the fragment != null I remove it, before creating and showing the new one. In code, what I usually do is:

    Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
    if (fragment != null) {
      getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }
    new CustomDialogFragment().show(getSupportFragmentManager(), FRAGMENT_TAG );