Traditional alert dialogs do not conform the lifecycle events when using fragments such as correctly handling back button presses or device rotations.
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.
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:
DialogFragment
and override the OnCreateDialog()
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(); } } }
AlertFragment frag = new AlertFragment();
Show()
method on the fragment to display it:frag.Show(SupportFragmentManager, "AlertFragment");
frag.Show(FragmentManager, "AlertFragment");
Dialogs can be used directly, but when using fragments they should be used with a DialogFragment
instance. These fragments are designed to work with dialogs. They follow the lifecycle of fragments but contain all that is needed for creating and displaying dialogs.
Using a DialogFragment
instance allows us to embed the dialog into an activity just like any other fragment. This gives us the extra flexibility to support embedding or popping up a dialog depending on the screen size or any other criteria.
In order to use dialog fragments, we have to inherit from the more specific DialogFragment
instance, instead of Fragment
, and override the OnCreateDialog()
method. In this method, we create the dialog as we would without fragments, but instead of invoking Show
, we return the actual dialog from the Create()
method.
When we want to display the dialog in a DialogFragment
instance, we invoke the Show()
method that is on the fragment, rather than the one on the dialog. We pass the FragmentManager
instance along with a tag to the Show()
method. The tag is used by the underlying fragment transaction.
As the DialogFragment
instance is just an extension of Fragment
, we can interact with the containing Activity
instance just as we would when overriding the base Fragment
instance. For example, we can interact with the activity when the fragment is attached to the activity. We can capture the instance of the activity by overriding the OnAttach()
method. When something happens in the dialog fragment, we can invoke methods or set properties on the activity.