Friday, June 13, 2014

Fragment as usual and as a Dialog

Short version

If you need to display a fragment as a usual fragment and as a Dialog. Just inherit it from DialogFragment. Call Show() if you want it as a dialog or add it as usual if you want it to behave as it would as a standard Fragment.

Long version

I spent a good hour trying to solve this in the most complicated ways imagenable. Now I'm just ashamed that I didn't try the most obvious.

I have an Android app that supports all kinds of screen sizes. One of the features is to do a stock search. On the phone it's a straight forward page by page search. Select the product, select some parameters, view result, view details. Each in a different fragment using the entire screen estate.

However, on a tablet with more space available the layout is different. The three first fragments are layed out to share the screen and the fourth (the details view) should be a dialog.

I tried to create a generic dialog wrapper to host my fragment. Of course, this did not work.

The solution, however, is quite simple.

Just inherit your fragment from DialogFragment instead of Fragment.

   1: if (_isDualPane)
   2: {
   3:     detailFragment.Show(this.SupportFragmentManager, "result_dialog");
   4: }
   5: else
   6: {
   7:     var ft= this.SupportFragmentManager.BeginTransaction();
   8:     ft.Replace(Android.Resource.Id.Content, detailFragment).AddToBackStack(null);
   9:     ft.Commit();
  10: }

The original stack overflow question

No comments:

Post a Comment