Friday 28 December 2012

Android: DialogFragment and screen rotation

If you're setting up your dialogs using the DialogFragment class, you've probably noticed that a dialog which is shown becomes hidden when the screen orientation is changed. Not great! Spending a fair bit of time looking into this - browsing online and Stack Overflow in particular - you'll find lots of discussion and suggestions but it becomes pretty clear very soon that nobody really quite knows what to do about it!! Below are a couple of things I tried:

(1) Included an empty (i.e. no arguments), public constructor in my DialogFragment class which simply calls the default, empty super constructor.

(2) Tried different combinations of setRetainInstance(true) and setRetainInstance(false) with getDialog().setDismissMessage(null) and getDialog().setOnDismissListener(null) in my DialogFragment.onCreate(Bundle savedInstanceState) and DialogFragment.onDestroyView() methods respectively.

In the end I gave up and am now allowing my dialogs to be dismissed on screen rotation by calling setRetainInstance(true) when my dialog is created (i.e. in my DialogFragment.onCreate(Bundle savedInstanceState) method). This causes the dialog to be dismissed proper on screen orientation change instead of simply showing as invisible whilst blocking the screen. Not ideal and it would have been great to have dialogs persist beyond screen rotations but better not to spend any more time on this shooting in the dark!