AlertDialog vs AlertDialog.Builder

Go To StackoverFlow.com

9

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?

2012-04-04 19:28
by stephenfin


7

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

2012-04-04 19:36
by jqpubliq
So it's 'kind of' like the istream/ostream operators in C++? That sounds reasonabl - stephenfin 2012-04-04 19:39


9

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.

2012-04-04 19:34
by waqaslam
But who does it help? Is its purpose just to concise everything into one long statement rather than multiple individual statements (setting the title etc?) or does it offer more functionality in some way - stephenfin 2012-04-04 19:37
yes, its for convenience to call methods in a chain to - waqaslam 2012-04-04 19:38
@stephenfin actually no - builder classes are not just for chaining method calls. they very often act like a factory which provide reasonable default values and customization options. also it's very common to for the product (AlertDialog) to be immutable/abstract while the factory counterparts are not which can tremendously ease the process of creating the product. take for example StringBuilder or ProcessBuilder - andr 2013-02-04 02:26
@andr You make a good point about immutability. You will run into this if you create an AlertDialog with an embedded WebView (hint: use AlertDialog.Builder if you want to see changes in the loaded url) - Cesar Maiorino 2014-01-27 19:34


1

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.

2013-02-04 01:53
by user1977094


0

I think that factory methods are just more convinient.

2012-04-04 19:33
by Igor Filippov
Ads