Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Best way of avoiding Dialogs to dismiss after a device rotation

After a long search around this forum, I found a lot of answers where people propose using solutions for avoiding dialogs to dismiss after rotation, just like:

android:configChanges="keyboardHidden|orientation"

Or override the following method, which appeared to be the most recommended:

protected Dialog onCreateDialog(int id)

But, after look around the Android Reference Documentation, I could notice that these Dialog methods are being deprecated.

So, the obvious question is:

Today, what is the best way of avoiding Dialogs to dismiss after a device rotation?

Thanks in advance.

like image 614
Jorge Gil Avatar asked Aug 15 '12 06:08

Jorge Gil


People also ask

What can be done to prevent a dialog from disappearing when the device gets rotated?

The best way to avoid this problem nowadays is by using a DialogFragment . Create a new class which extends DialogFragment . Override onCreateDialog and return your old Dialog or an AlertDialog .

How do you handle rotation on Android?

If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.


2 Answers

You should now use DialogFragment from new Fragments API. To use it on the platform lower, than 3.0, use compatibility package.

like image 192
Vladimir Ivanov Avatar answered Sep 27 '22 16:09

Vladimir Ivanov


what I'm gonna answer is based on Dialogs alone (NOT dialogfragment which are a whole different game).

Dialogs are part of the activity, and as such, they are being destroyed during the rotation. References that you used to have to the dialog will now point to a dialog that it's not on screen anymore, and likely to cause you problems.

Unfortunately there's no easy solution. With android:configChanges="keyboardHidden|orientation" you'll be creating an array of other problems for yourself.

The way to do is to save any configuration of the dialog, dismiss it, and whenever the activity is being re-created, re-create the dialog.

like image 34
Budius Avatar answered Sep 27 '22 18:09

Budius