In this lesson, we'll be creating an
AlertDialog to prompt our users for a locationName for a calculated tip and a menu option for the user to access the dialog. After the user enters the location name and taps save, we'll pop up an Android
SnackBar indicating that we've saved it. Through this process, you will learn how to properly create an
AlertDialog, using a
DialogFragment, which survives, while maintaining it's state; and how to build an Android
Menu to display this dialog.
Key concepts in this lesson that you will learn:
- How to build an AlertDialog
- Make sure the dialog stays open after the device rotates
- Retain the state of the dialog once rotated so that the user doesn't loose everything they've typed
- How to attach a listener to the Dialog that receives the text the user entered on save
- How to build an Android Menu to display the dialog to the user
Hi Max, isn't the DialogFragment a god object here? What about creating a ViewModel for the DialogFragment?
Hi there, I see you point, you could introduce a ViewModel to back this dialog. In fact, in the next lesson we create a dialog fragment to load a previously saved tip and leverage a ViewModel to access the list of tips that have been saved.
There's no firm rule here, but the rule I generally follow is to not place presentation logic in the View. In this case , this DialogFragment doesn't have any presentation logic (short of not invoking the callback if the text is empty). It's just capturing the data and passing the result back to the hosting Activity which in turn is directly passing that back to the ViewModel. For that reason, I don't consider it necessary to use a ViewModel. But, certainly it's not wrong to introduce a ViewModel here as you're suggesting.
This explanation of the pattern is an introductory view into it. From there, each team usually has its own special nuances in which they change things up - and thats ok.
Hope that helps! :-)