Reputation: 22126
As far as I can tell, there are two ways to show a Dialog from an Activity.
AlertDialog.Builder
), and then call the newly created Dialog's show()
method.showDialog()
method, passing in an int that uniquely defines what sort of Dialog you want to build. Then override onCreateDialog()
to actually build the Dialog, and Android will display it for you.The second method seems to be the standard practice but I'm curious if there is any reason it matters which one I use. Here's all I can come up with:
Reasons to use Dialog.show
Activity.showDialog
, as described in this question. You may have to store a String or something in a member variable, just so that it can be retrieved moments later during onCreateDialog
or onPrepareDialog
.showDialog()
switch
statement in the overridden onCreateDialog
methodswitch
statement in the overridden onPrepareDialog
methodReasons to use Activity.showDialog
:
Activity.showDialog
say that the Dialog is "managed" by the Activity which I suppose provides some benefit? But this is also true if you use the AlertDialog.Builder
, I would think, because you pass in this
as an argument to the Builder's constructor. So my question is, what are the criteria for deciding when to use Activity.showDialog
and when to use Dialog.show
, and why?
Upvotes: 37
Views: 33926
Reputation: 28737
You can use the overloaded method showDialog(int, Bundle)
introduced in API level 8.
Simple shove the message to be shown into the bundle, which will be available in onPrepareDialog(int, Dialog, Bundle)
.
Yes, I know that showDialog()
itself has been deprecated now.
Upvotes: 2
Reputation: 8700
In my opinion you should prefer showDialog
because this method will do most of the work for you. In example You don't have to worry that you will lose reference to your dialog after changing screen orientation. It will be recreated automatically. Dialog.show
is much more prone to errors.
So I suggest you to use showDialog
everywhere you can.
Upvotes: 18
Reputation: 200140
I think the decision is up to you, depending on the good reasons you have pointed out. If I have an activity which has just one dialog (say, for displaying an alert) I'd just fire the Dialog.show
method... on the other hand, if the UI of my app relies too much of its functionality on the use of dialogs it'd be much better to use showDialog()
. I think the best advantage of using showDialog()
is that it's easier to read:
final int ERROR_DIALOG = 404;
final int MSG_DIALOG = 200;
.....
// if someone else read this, he/she will immediately understand what's going on
showDialog( ERROR_DIALOG );
Upvotes: 2