Alert fragments
Traditional alert dialogs do not conform the lifecycle events when using fragments such as correctly handling back button presses or device rotations.
Getting ready
If we are going to support Android versions prior to 3.0, we will have to install the Xamarin Support Library v7 AppCompat NuGet or component into our project.
How to do it...
Using a dialog in a DialogFragment
instance ensures that the dialog correctly handles the lifecycle events. We override the OnCreateDialog()
method to create the dialog:
To create an alert fragment, we inherit from
DialogFragment
and override theOnCreateDialog()
method. In this method, we create and return the dialog:public class AlertFragment : DialogFragment { public override Dialog OnCreateDialog(Bundle savedState) { using (var alert = new AlertDialog.Builder(Activity)) { dialog.SetTitle("Alert Title"); dialog.SetMessage("Alert message text here..."); return alert.Create(); } } }
When it is going to be displayed...