Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using a DialogFragment over simple AlertDialog?

I've read several stackoverflow.com answers, but still don't see the advantage of using a DialogFragment over a simple AlertDialog. I have, apparently, two strategies:

a) use an AlertDialog.Builder to configure an AlertDialog, .create() it, and then .show() it in my Activity (in some button handler), or

b) subclass DialogFragment, write the same AlertDialog-building code in onCreateDialog() (except I just return the .create(), and then, in my Activity, instantiate a DialogFragment, and show it.

The output looks the same.

Either way, I am not using deprecated code -- I am using .show() with both the AlertDialog or the DialogFragment. Is the advantage when I go to another sized device? Or what's the point ...

Thanks for any insights,

Michael

like image 842
Michael Rogers Avatar asked Feb 10 '13 22:02

Michael Rogers


People also ask

What is DialogFragment used for?

DialogFragment is a utility class which extends the Fragment class. It is a part of the v4 support library and is used to display an overlay modal window within an activity that floats on top of the rest of the content. Essentially a DialogFragment displays a Dialog but inside a Fragment.

What is the difference between dialog & DialogFragment?

Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.

What is the difference between dialog and AlertDialog?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .

Is DialogFragment deprecated?

This method is deprecated. androidx.


2 Answers

DialogFragment handles a number of lifecycle management cases for you including configuration changes (e.g. screen rotation) and state restoration if your app's process is killed in the background and the user returns to it later. If you're not using DialogFragment you will need to handle cases like this in another way.

like image 76
adamp Avatar answered Oct 15 '22 05:10

adamp


In addition to what @adamp said, since DialogFragment is getting its own lifecycle callbacks, it would be responsible for its lifecycle, so your activity won't be responsible to tell it what to do.

For example when activity is finishing, your activity should tell the dialogs to dimiss(), otherwise you'll see it has leaked the window error in logcat.

like image 33
Sadegh Avatar answered Oct 15 '22 04:10

Sadegh