Search code examples
androidandroid-fragmentsdialogandroid-dialogfragment

Can i use a `DialogFragment` for a simple yes/no dialog instead of `AlertDialog`? What are the adavntages?


According to the docs in Android Developers,

Using DialogFragment to manage the dialog ensures that it correctly handles lifecycle events such as when the user presses the Back button or rotates the screen. The DialogFragment class also allows you to reuse the dialog's UI as an embeddable component in a larger UI, just like a traditional Fragment (such as when you want the dialog UI to appear differently on large and small screens).

But i get the same behavior in an Alert Dialog too... That is,there is no affect on the Alert Dialog even if i rotate the screen or press the back button.

Then why should i use Dialog Fragment instead of Alert Dialog?


Solution

  • DialogFragment is a specialized Fragment shaped as a dialog, while AlertDialog is a specialized Dialog. A fragment can be bound to the Activity at runtime, so for instance using a DialogFragment for your dialogs will allow you to re-use the same dialog on multiple activities, without having each activity to handle all the code separately. I definitely recommend to use DialogFragment over AlertDialog.