问题
Why would one use the AlertDialog.Builder
class rather than the methods directly available to AlertDialog
,
For example, why use AlertDialog.Builder.setCancellable
rather than AlertDialog.setCancellable
? Surely this is a case of redundancy?
回答1:
Because AlertDialog.setCancellable
returns void and AlertDialog.Builder.setCancellable
returns an AlertDialog.Builder
.
This means that the builder allows you to chain a bunch of settings with a little less verbosity. It's just a convenience class
回答2:
AlertDialog allows you to show a dialog above your activity/fragment. It is usually used for prompting user for interaction including few buttons or notifying for something.
AlertDialog.Builder is an inner static class of AlertDialog which allows you to quickly setup a dialog with its handy methods. Its just like a helper class to AlertDialog. It is used for calling methods in a chain.
回答3:
AlertDialog.Builder
does the settings of the attributes such as setTitle()
or setMessage()
and are not displayed to the user.
AlertDialog
is the one that displays those attributes which have been set in the AlertDialog.Builder
.
The purpose of having both as mentioned somewhere is that it allows settings to be made separately from the actual displaying which in turn makes thing convenient.
回答4:
I think that factory methods are just more convinient.
来源:https://stackoverflow.com/questions/10017951/alertdialog-vs-alertdialog-builder