I am trying to prevent dialogs built with Alert builder from being dismissed when the Activity is restarted.
If I overload the onConfigurationChanged method I can successfully do this and reset the layout to correct orientation but I lose sticky text feature of edittext. So in solving the dialog problem I have created this edittext problem.
If I save the strings from the edittext and reassign them in the onCofiguration change they still seem to default to initial value not what was entered before rotation. Even if I force an invalidate does seem to update them.
I really need to solve either the dialog problem or the edittext problem.
Thanks for the help.
A very easy approach is to create the dialogs from the method
onCreateDialog()
(see note below). You show them throughshowDialog()
. This way, Android handles the rotation for you and you do not have to calldismiss()
inonPause()
to avoid a WindowLeak and then you neither have to restore the dialog. From the docs:See Android docs showDialog() for more info. Hope it helps somebody!
Note: If using AlertDialog.Builder, do not call
show()
fromonCreateDialog()
, callcreate()
instead. If using ProgressDialog, just create the object, set the parameters you need and return it. In conclusion,show()
insideonCreateDialog()
causes problems, just create de Dialog instance and return it. This should work! (I have experienced issues using showDialog() from onCreate() -actually not showing the dialog-, but if you use it in onResume() or in a listener callback it works well).This question was answered a long time ago.
Yet this is non-hacky and simple solution I use for myself.
I did this helper class for myself, so you can use it in your application too.
Usage is:
Or
Just add android:configChanges="orientation" with your activity element in AndroidManifest.xml
Example:
Just use
and app will know how to handle rotation and screen size.
The best way to avoid this problem nowadays is by using a
DialogFragment
.Create a new class which extends
DialogFragment
. OverrideonCreateDialog
and return your oldDialog
or anAlertDialog
.Then you can show it with
DialogFragment.show(fragmentManager, tag)
.Here's an example with a
Listener
:And in the Activity you call:
This answer helps explain these other three questions (and their answers):